关于fopen()与fclose()使用中遇到的问题: r+模式下无法写入文件; 解决方案:使用fclose关闭文件后重新fopen

要求如下:
We need to remove the non-ASCII bytes from files.

Write a C program, leave_only_ascii.c, which takes one argument, a filename.

leave_only_ascii.c should remove all non-ASCII bytes from the file.

After it is run the file should contain only a ASCII bytes.

It should print nothing on stdout. It should only change the file.

Assume a byte is non-ASCII if it contains a value between 128…255 inclusive.

有问题的代码如下:
(没有error checking)

#include <stdio.h>
int main (int argc, char **argv) {
	// open the file without error checking
    FILE *input_stream = fopen(argv[1], "r+");
    FILE *output_stream = fopen("temp", "w+");
    // read from input file and put the output into file called temp
    int input = -1;
    input = fgetc(input_stream);
    while(input != EOF) {
        if (input < 128) {
            fputc(input, output_stream);
        }
        input = fgetc(input_stream);
    }
    // rewrite the input file
    input = fgetc(output_stream);
    while(input != EOF) {
        fputc(input, input_stream);
        input = fgetc(output_stream);
    }
    fclose(input_stream);
    fclose(output_stream);
    return 0;
}

但是发现了一个问题,那就是在temp文件中的输出是正确的,但是argv[1]所指的的文件始终没有变化。

这里确实应该出现问题,因为在fgetc和fputc之后,文件的指针都指向了文件末尾,那么也就没法从temp文件里面读取数据了。我尝试了在重写文件前加入fseek(output_stream, 0, SEEK_SET);以及fseek(input_stream, 0, SEEK_SET);但是依然不能改变argv[1]文件的内容,很奇怪,既然fopen打开是r+模式,那应该可以读出和写入。如果有哪里理解错误请指出。

于是我换了一种暴力的方式:在读取结束后直接fclose文件,然后重新fopen,这样就可以初始化指针,以及更换读取模式:

#include <stdio.h>
int main (int argc, char **argv) {
    FILE *input_stream = fopen(argv[1], "r+");
    FILE *output_stream = fopen("temp", "w+");
    int input = -1;
    input = fgetc(input_stream);
    while(input != EOF) {
        if (input < 128) {
            fputc(input, output_stream);
        }
        input = fgetc(input_stream);
    }

	//
    // revised
    fclose(input_stream);
    fclose(output_stream);
    output_stream = fopen(argv[1], "w+");
    input_stream = fopen("temp", "r+");
    input = fgetc(input_stream);
	//
	
    while(input != EOF) {
        fputc(input, output_stream);
        input = fgetc(input_stream);
    }
    fclose(input_stream);
    fclose(output_stream);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值