【发布时间】:2018-02-22 01:12:27
【问题描述】:
#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);
}
我有上面我理解的代码。我怀疑当我附加字符串“模板字符串 3:”时,我的 fp 将内容添加到文件末尾的文件 test.txt 并且在添加 fp 之后应该指向文件末尾(我希望)但是如果我使用fgets 将文件的内容从 fp 读取到 buff 它应该具有的内容。谁能解释一下此时发生了什么。
【问题讨论】:
-
请勿发文字图片
-
使用
(FILE *)fp定义为FILE*fp;的变量的强制转换是“无害的”但可笑的。