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;
}