C语言文件操作中rewind()函数使用错误问题求助
使用rewind()后无法读取文件内容的解决方法
问题背景
现有一段C语言程序,核心功能为:
- 修正输入文件中的负访客数为0,写入
corrected.txt - 计算修正后文件的访客数平均值
- 找出访客数最多的日期的日数
程序要求必须在main函数中使用rewind(),但当前调用rewind()后,averageValue和maxVisit函数中的fscanf循环完全不执行,输出错误结果:
Average value: -nan Day with the highest amount of visitors: 0
若关闭文件再以读模式重开则可正常运行,但不符合任务要求。
完整代码
#include <stdio.h> void correctNumbers(FILE* input, FILE* output) { int year, month, day; int amount; while (fscanf(input, "%d-%d-%d,%d", &year, &month, &day, &amount) == 4) { if (amount < 0) { amount = 0; } fprintf(output, "%d-%d-%d,%d\n", year, month, day, amount); } } double averageValue(FILE* output){ double sum = 0; double total = 0; int year, month, day, amount; /*fclose(output); output = fopen("corrected.txt", "r");*/ while(fscanf(output, "%d-%d-%d,%d", &year, &month, &day, &amount) == 4){ total++; sum += amount; } printf("Average value: %.2lf\n", sum/total); return sum/total; } void maxVisit(FILE* output) { int year, month, day, amount; int maxDay; int maxVisitors = -1; /*fclose(output); output = fopen("korrigiert.txt", "r");*/ while (fscanf(output, "%d-%d-%d,%d", &year, &month, &day, &amount) == 4) { if (amount >= maxVisitors) { maxDay = day; maxVisitors = amount; } } printf("Day with the highest amount of visitors: %d\n", maxDay); } int main(int argc, char* argv[]){ FILE* input; FILE* output; if(argc < 2){ printf("Pls include a filename\n"); return 0; }else{ input = fopen(argv[1], "r"); output = fopen("corrected.txt", "w"); if(input == NULL || output == NULL){ printf("File doesnt exist or failed to open\n"); return 0; } } correctNumbers(input, output); rewind(output); averageValue(output); rewind(output); maxVisit(output); fclose(input); fclose(output); return 0; }
输入输出预期
- 输入文件内容:
2021-10-05,-3 2021-10-06,-2 2022-02-02,7 2022-02-03,10 2022-02-04,9
- 修正后文件内容:
2021-10-5,0 2021-10-6,0 2022-2-2,7 2022-2-3,10 2022-2-4,9
- 预期程序输出:
Average value: 4.50 Day with the highest amount of visitors: 3
问题根源
当前代码中,output文件是以"w"模式打开的,该模式仅支持写操作,不允许读操作。即使调用rewind()将文件指针移到文件开头,后续的fscanf仍然无法读取内容,导致循环不执行:
averageValue中total保持0,sum/total得到-nanmaxVisit中循环未执行,maxDay未被赋值,输出初始垃圾值0
解决方法
将output文件的打开模式改为"w+",该模式支持读写操作,同时保留"w"模式的创建/截断文件特性。此外,建议在写操作完成后调用fflush(),确保缓冲区内容全部写入文件,再执行rewind()。
修改后的main函数代码
int main(int argc, char* argv[]){ FILE* input; FILE* output; if(argc < 2){ printf("Pls include a filename\n"); return 0; }else{ input = fopen(argv[1], "r"); // 改为w+模式,支持读写 output = fopen("corrected.txt", "w+"); if(input == NULL || output == NULL){ printf("File doesnt exist or failed to open\n"); return 0; } } correctNumbers(input, output); // 刷新缓冲区,确保所有写入内容都落盘 fflush(output); rewind(output); averageValue(output); rewind(output); maxVisit(output); fclose(input); fclose(output); return 0; }
验证结果
修改后运行程序,将得到预期输出:
Average value: 4.50 Day with the highest amount of visitors: 3
内容的提问来源于stack exchange,提问作者R0gue
相关产品推荐
相关产品推荐

