在"file1.dat"我写的文件中"anahasapples".
然后我写了这个程序:
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *ptr_file;
ptr_file=fopen("file1.dat","r+");
printf("%c",fgetc(ptr_file));
printf("%c",fgetc(ptr_file));
printf("%c\n",fgetc(ptr_file));
char c;
printf("char:\n");
c=getch();
fputc(c,ptr_file);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我从文件打印前3个字符的部分工作.之后,我想在文件中加入一个字符.
当我编译它时,我没有得到任何错误,但包含文本不会改变.
fopen()的文档标准地显示以下说明:
当使用更新模式打开文件(+作为mode参数中的第二个或第三个字符)时,可以在关联的流上执行输入和输出.但是,输入不能直接跟随输入而不干涉fflush(3C)或文件定位功能(fseek(3C),fsetpos(3C)或倒带(3C)),输入不能直接跟随输入除非输入操作遇到文件结尾,否则输出时不会调用文件定位功能.
只需在代码中添加一个fseek(),一切运行良好:
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *ptr_file;
ptr_file=fopen("file1.dat","r+");
printf("%c",fgetc(ptr_file));
printf("%c",fgetc(ptr_file));
printf("%c\n",fgetc(ptr_file));
char c;
printf("char:\n");
c=getch();
fseek( ptr_file, 0, SEEK_CUR ); /* Add this line */
int err = fputc(c,ptr_file);
printf ("err=%d\n", err);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是输入'x'之前和之后的file1.dat:
之前
anahasapples
后
anaxasapples
似乎默认情况下fputc()尝试写入文件的末尾,因此您需要重新定位文件指针(例如,使用fseek)以使写入发生在当前文件指针的位置.