以下のコードでは、行の後の開始位置へのファイル ポインターをシークした後にデータを書き込むと、余分なスペース (約 300 スペース) が追加されます。
fseek(fp1,0,SEEK_SET);
2 番目の fputs() 関数呼び出しをコメントしても問題はありません。また、入力されたデータは最後に追加されず、代わりにスペースのみが追加されます。問題を特定できません。
TDM-GCC-64 コンパイラを使用しています。
テスト用に、file1.txt の先頭に「Welcome to You All」という内容が含まれていました。入力データ: "Today" プログラム実行後の出力: "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;
}