Last line repeats when doing fgets/fputs

只谈情不闲聊 提交于 2019-12-24 21:17:41

问题


I'm doing an insertion, that imply a file, a string, and a new file who will receive all the data of the original file plus the string to be inserted, and it will replace the original file.

So, for example, my original file:

data.txt

 line1
 line2
 line3
 line4
 line5 

will become, with the insertion of the string "newline":

data_temp.txt --> renamed later data.txt

 line1
 line2
 line3
 line4
 line5 
 newline

With that purpose, I have the following code:

/* 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");   

My problem is basically in the writing to the original file, to the new file. The last line of the original file shows duplicated in the new file.

In the example given:

data.txt

 line1
 line2
 line3
 line4
 line5 

The line5 (last line of the original file) is showed twice on the new file, and then is the string to be inserted.

data_temp.txt --> renamed later data.txt

 line1
 line2
 line3
 line4
 line5 
 line5
 newline

I strongly believe the problem is in the reading of the original file (AKA the while(!feof(data)) loop), on the checking the EOF, the fgets, or the fputs. Any idea to solve this?


回答1:


Correct. The problem is in your loop condition.

feof() is evil because it's often misunderstood. feof() doesn't indicate that you are at the end-of-file. It only indicates that it has not yet encountered it (that you haven't fetched a byte past the end of the file).

You must instead detect within the loop when you encounter EOF(when fgets() returns NULL) and break out of the loop then.



来源:https://stackoverflow.com/questions/20037773/last-line-repeats-when-doing-fgets-fputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!