我正在用C编写一个非常简单的文件读/写程序。当我尝试测试代码时,输出不是我所期望的。这是我的代码:
#include <stdio.h>
void hwrite(FILE *fp, int count, char *str) {
fprintf(fp, "%d ""%s", count, str);
}
void hread(FILE *fp) {
if(fp != NULL) {
char line [128];
while(fgets(line, sizeof line, fp) != NULL) {
fputs(line, stdout);
}
fclose(fp);
}
else {
perror("xxx.txt");
}
}
int main(void) {
int count = 1;
char *str = "test text\n";
FILE *fp;
fp = fopen("xxx.txt", "a");
int i;
for (i = 0; i < 3; i++) {
hwrite(fp, count, str);
count = count+1;
}
fp = fopen("xxx.txt", "r");
hread(fp);
return 0;
}
该程序编译没有问题。然后我执行一次a.out命令,没有输出。我是第二次这样做,并且有一个输出,但它不完整。这里:
[xxxxx xxx]> a.out
[xxxxx xxx]> a.out
1 test text
2 test text
3 test text
然后我打开文件找到这个:
1 test text
2 test text
3 test text
1 test text
2 test text
3 test text
为什么输出中没有显示?谢谢你的时间。
答案 0 :(得分:4)
您永远不会刷新输出,因此在程序退出之前它实际上不会写入文件。特别是,它在读取文件后将输出写入文件。在重新打开阅读之前尝试fclose
。
int main(void) {
int count = 1;
char *str = "test text\n";
FILE *fp;
fp = fopen("xxx.txt", "a");
int i;
for (i = 0; i < 3; i++) {
hwrite(fp, count, str);
count = count+1;
}
fclose(fp); /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
fp = fopen("xxx.txt", "r");
hread(fp);
return 0;
}