在下面的代码中,如果在搜索到行后的起始位置的文件指针后写入数据,则会追加额外的spcaes(可能大约300个空格)
fseek(fp1,0,SEEK_SET);
如果我评论第二个fputs()函数调用,则没有问题。 此外,输入的数据不会在末尾附加,而是仅添加空格。 我无法确定问题。
我正在使用TDM-GCC-64编译器。
出于测试目的,file1.txt在开头有内容“欢迎大家”。 输入数据:“今天” 执行程序后的输出:“Todayme to You All”,后跟许多空格。
int main()
{
FILE *fp1;
char ch;
char data[50];
fp1=fopen("file1.txt", "r+");
if(fp1==NULL)
{
printf("Error in Opening the file\n");
return(0);
}
printf("Read and Write Mode. The data in the file is\n");
while((ch=getc(fp1))!=EOF)
{
putc(ch,stdout);
}
// Write some data at the end of the file
printf("\nEnter some data to be written to the file\n");
gets(data);
fseek(fp1,0,SEEK_END);
fputs(data,fp1);
fseek(fp1,0,SEEK_SET);
fputs(data,fp1);
printf("data in file after write operation is\n");
while((ch=getc(fp1))!=EOF)
{
putc(ch,stdout);
}
fclose(fp1);
return 0;
}
答案 0 :(得分:1)
您应该查看fopen
文档中的细则:
在更新模式('+')中,可以执行输入和输出,但是如果没有对fflush,fseek,fsetpos或rewind进行干预调用,则输入后不能输入,并且输入不能在没有干预的情况下输出调用fseek,fsetpos或rewind,除非输入操作遇到文件结尾。
读取和写入可能是缓冲的,但仍然共享一个文件位置。在不警告运行时(fseek
)的情况下切换模式可能会导致缓冲。就像你注意到了一样!