c - extra spaces written in r+ mode
问题描述
In the code below, extra spcaes (may be around 300 space) are getting appended if I write data after seeking the file pointer to the start position after the line
fseek(fp1,0,SEEK_SET);
If I comment second fputs() function call, there is no issue. Also the inputted data is not getting appended at the end, instead only spaces are getting appended. I am unable to identify the problem.
I am using TDM-GCC-64 compiler.
For testing purpose, file1.txt had contents "Welcome to You All" at the beginning. Inputted data: "Today" Output after execution of the program: "Todayme to You All" followed by many spaces.
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;
}
解决方案
You should check the fine print in the fopen
documentation:
In update mode ('+'), both input and output may be performed, but output cannot be followed by input without an intervening call to fflush, fseek, fsetpos or rewind, and input cannot be followed by output without an intervening call to fseek, fsetpos or rewind, unless the input operation encountered end of file.
Reading and writing might be buffered, but still share a single file position. Switching modes without alerting the runtime (fseek
) could mess up the buffering. Like you have noticed!
推荐阅读
- node.js - Provide value from node to angular universal
- puppet - Deep hiera lookup in a ruby template returns last result only
- node.js - 使用 nodejs 从 newman 加载 csv
- python - Adding values from one list to another when they share value
- html - 如何将固定高度的div中的元素垂直对齐?
- c# - 即使我之前声明过我的变量声明也没有检测到
- java - JavaFX 图表未正确分层
- java - 选择要继续的实例
- python - 比较向量列表
- javascript - 在 Gridview 中启用/禁用文本框