为什么执行了不显示内容?
(hello.txt存在)里面内容也是I am not you,I am only your passer.
把 fputs ("I am not you,I am only your passer.", fp); 注释掉后就显示是内容
# include <stdio.h>
# include <stdlib.h>
int main (void)
{
FILE * fp;
char ch[100];
fp = fopen ("hello.txt", "r+");
fputs ("I am not you,I am only your passer.", fp);
fgets (ch, 100, fp);
printf ("%s", ch);
fclose (fp);
return 0;
}
Process exited after 0.8467 seconds with return value 0
请按任意键继续. . .
(注释掉后的)
结果:
I am not you,I am only your passer.
Process exited after 0.06704 seconds with return value 0
请按任意键继续. . .
【以下回答由 GPT 生成】
问题的原因是在执行完fputs
函数之后,文件指针已经移动到了文件的末尾,然后再执行fgets
函数时,由于文件指针已经在文件末尾,所以无法成功读取文件内容。因此,在执行fgets
函数之前,需要将文件指针重新定位到文件的开头。
下面是修改后的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char ch[100];
fp = fopen ("hello.txt", "r+");
if (fp == NULL) {
printf("Failed to open the file.\n");
return 1;
}
fputs ("I am not you,I am only your passer.", fp);
// 重新定位文件指针到文件开头
fseek(fp, 0, SEEK_SET);
fgets (ch, 100, fp);
printf ("%s", ch);
fclose (fp);
return 0;
}
在修改后的代码中,我使用了fseek
函数将文件指针重新定位到文件的开头,然后再执行fgets
函数,就可以成功读取文件的内容并显示在控制台上了。
请尝试使用修改后的代码来执行,应该能够解决你的问题。如果还有其他疑问,请随时提出。
你的fopen打开方式是 读取 ,fputs 是写入