【发布时间】:2018-05-13 21:59:25
【问题描述】:
在下面的代码中,如果我在寻找指向行后起始位置的文件指针后写入数据,则会附加额外的 spcaes(可能是大约 300 个空间)
fseek(fp1,0,SEEK_SET);
如果我评论第二个 fputs() 函数调用,则没有问题。 此外,输入的数据不会在最后附加,而是只附加空格。 我无法确定问题所在。
我正在使用 TDM-GCC-64 编译器。
出于测试目的,file1.txt 开头有“Welcome to You All”的内容。 输入数据:“今天” 程序执行后的输出:“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;
}
【问题讨论】:
-
只是指出要避免这种用法,getchar 的返回类型是 int。您捕获的返回值在 char ch 中。
-
无法复制。我在文件的开头和结尾都插入了“今天”。根本没有多余的空间。 BTW:在最后一次打印文件之前,如果你想打印整个文件,你应该添加一个
fseek(fp1,0,SEEK_SET);。 -
OT:永远不要使用
gets -
@4386427 你能告诉我你用的是什么编译器吗?我的朋友还说他在 MinGW 中没有遇到问题
-
OT:
char ch;==>int ch;