如何修复C中简单文件读/写程序的输出?
我正在用C编写一个非常简单的文件读/写程序。当我尝试测试代码时,输出不是我所期望的。这是我的密码:如何修复C中简单文件读/写程序的输出?,c,file,unix,C,File,Unix,我正在用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];
#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;
}
然后我打开该文件以查找以下内容:
1 test text
2 test text
3 test text
1 test text
2 test text
3 test text
为什么在输出中没有显示这一点?谢谢您的时间。您从不刷新输出,因此在程序退出之前,它不会真正写入文件。特别是,它在读取文件后将输出写入文件。重新打开阅读前,请尝试关闭
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;
}
int main(无效){
整数计数=1;
char*str=“测试文本\n”;
文件*fp;
fp=fopen(“xxx.txt”,“a”);
int i;
对于(i=0;i<3;i++){
hwrite(fp、count、str);
计数=计数+1;
}
fclose(fp);/*您从不刷新输出,因此在程序退出之前它不会实际写入文件。特别是,它在读取文件后将输出写入文件。请在重新打开读取之前尝试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;
}
int main(无效){
整数计数=1;
char*str=“测试文本\n”;
文件*fp;
fp=fopen(“xxx.txt”,“a”);
int i;
对于(i=0;i<3;i++){
hwrite(fp、count、str);
计数=计数+1;
}
fclose(fp);/*我正在尝试,它会编译,但当我尝试运行它时,会出现内存映射。编辑:没关系,我不小心调用了fclose两次。它可以工作。谢谢我正在尝试,它会编译,但当我尝试运行它时,会出现内存映射。编辑:没关系,我不小心调用了fclose两次。它可以工作。谢谢