要求如下:
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;
}