C语言编程实现在一个文件末尾写入一段话并将文本文件全部显示在显示屏上

如题,程序没有报错但为什么没有显示出文件的全文啊
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp;
char ch;
char str[102] = {0}, strTemp[100];
if( (fp=fopen("D:\\demo.txt", "at+")) == NULL ){
printf("Cannot open file, press any key to exit!\n");
getch();
exit(1);
}
printf("Input a string:");
gets(strTemp);
strcat(str, "\n");
strcat(str, strTemp);
fputs(str, fp);
while( (ch=fgetc(fp)) != EOF ){
putchar(ch);
}
fclose(fp);
system("pause");
return 0;
}

你的文件指针位置不对,你放完字符串后,文件指针指向你放完字符串的地方,输出自然是从指针开始的

解决方法:fputs与循环之间加一个

fseek(fp, 0l, SEEK_SET);//将文件指针指向文件头

就可以了

温馨提示:答案为网友推荐,仅供参考