私は挿入を行っています。これは、元のファイルのすべてのデータと挿入される文字列を受け取るファイル、文字列、および新しいファイルを意味し、元のファイルを置き換えます。
たとえば、元のファイルは次のとおりです。
data.txt
line1
line2
line3
line4
line5
文字列「改行」を挿入すると、次のようになります。
data_temp.txt --> 後で名前を変更したdata.txt
line1
line2
line3
line4
line5
newline
その目的で、次のコードがあります。
/* FILE variables of the original file and the new file */
FILE *data, *data_temp;
data = fopen( "data.txt", "r" );
data_temp = fopen( "data_temp.txt", "w" );
/* String buffer */
char buf[256];
int i_buf;
/* The string to be inserted in the new file */
char newline[10] = "newline";
/* For each line of the original file, the content of each line
is written to the new file */
while(!feof(data))
{
/* Removing the \n from the string of the line read */
fgets(buf, MAX_INSERT, data);
for(i_buf = strlen(buf)-1; i_buf && buf[i_buf] < ' '; i_buf--)
buf[i_buf] = 0;
/* Writing the string obtained to the new file */
fputs(buf, data_temp);
fputs("\n", data_temp);
}
/* The string will be inserted at the final of the new file */
if(feof(datos))
{
fputs(newline, datos_temp);
}
/* Closing both files */
fclose(data);
fclose(data_temp);
/* The original file is deleted and replaced with the new file */
remove ("data.txt");
rename ("data_temp.txt", "data.txt");
私の問題は基本的に、元のファイル、新しいファイルへの書き込みにあります。元のファイルの最後の行は、新しいファイルに複製されて表示されます。
与えられた例では:
data.txt
line1
line2
line3
line4
line5
line5 (元のファイルの最後の行)は、新しいファイルで 2 回表示され、次に挿入される文字列です。
data_temp.txt --> 後で名前を変更したdata.txt
line1
line2
line3
line4
line5
line5
newline
問題は、元のファイル (AKAwhile(!feof(data))ループ) の読み取り、EOF、fgets、または fputs のチェックにあると強く信じています。これを解決するアイデアはありますか?