在执行fgets / fput时重复最后一行

时间:2013-11-17 23:48:42

标签: c string file fgets fputs

我正在进行插入,意味着文件字符串,以及新文件将接收所有原始文件的数据加上要插入的字符串,它将替换原始文件。

因此,例如,我的原始文件:

data.txt中

 line1
 line2
 line3
 line4
 line5 

将成为,插入字符串“newline”:

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 

第5行(原始文件的最后一行)在新文件上显示两次,然后是要插入的字符串。

data_temp.txt - &gt;稍后重命名 data.txt

 line1
 line2
 line3
 line4
 line5 
 line5
 newline

我坚信问题在于读取原始文件(AKA while(!feof(data))循环),检查EOF,fgets或fputs。有什么想法解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

正确。问题出在你的循环条件中。

feof()是邪恶的,因为它经常被误解。 feof()并不表示您 at 文件结尾。它只表示它还没有遇到它(你没有在文件末尾读取一个字节)。

当你遇到EOF时(当fgets()返回NULL时),你必须在循环内进行检测,然后突破循环。

相关问题