#include<stdio.h>
int main()
{
FILE *fp;
char buff[255];
fp=fopen("test.txt","w");
printf("File test.txt in w mode\n");
fprintf(fp,"Template string 1:\n");
fputs("Template string 2:",fp);
printf("File test.txt is created at local path\n\n");
fclose(fp);
fp=fopen("test.txt","r");
printf("\n\nFile test.txt in r mode\n");
fscanf(fp,"%s",buff);
printf("The content of the file test.txt using fscanf() is:\n%s\n",buff);
fgets(buff,255,(FILE *)fp);
printf("The content of the file test.txt using fgets() is :\n%s\n",buff);
fgets(buff,255,(FILE *)fp);
printf("The content of the file using fgets() is :\n%s\n",buff);
fclose(fp);
fp=fopen("test.txt","a");
printf("\n\nFile test.txt in a mode\n");
fprintf(fp,"Template String 3:\n");
fgets(buff,255,(FILE *)fp);
printf("After append %s\n",buff);
fclose(fp);
fp=fopen("test.txt","r+");
printf("File test.txt in r+ mode\n");
fgets(buff,255,(FILE *)fp);
printf("\n\nThe content of the file test.txt in r+ mode is:\n%s\n",buff);
fclose(fp);
}
我有上面的代码,我理解。我怀疑当我追加字符串&#34;模板字符串3:&#34;我的fp将内容添加到文件末尾的文件test.txt
,添加fp之后应该指向文件末尾(我希望)但是如果我使用fgets
来读取文件的内容fp到它应该拥有的buff。任何人都可以解释此时发生的事情。
答案 0 :(得分:0)
C库函数char *fgets(char *str, int n, FILE *stream)
从指定的流中读取一行并将其存储到str指向的字符串中。当读取(n-1)个字符,读取换行符或达到文件结尾时(以先到者为准),它会停止。
这就是为什么代码的最后一部分只显示文件的第一行。你没有获得printf("After append %s\n",buff);
输出的原因是此时文件指针位于EOF
。
当您cat
文件时,您会看到所有行都在那里。