0

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

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

数据.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");   

我的问题基本上是写入原始文件,写入新文件。原始文件的最后一行在新文件中显示重复

在给出的示例中:

数据.txt

 line1
 line2
 line3
 line4
 line5 

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

data_temp.txt --> 稍后重命名data.txt

 line1
 line2
 line3
 line4
 line5 
 line5
 newline

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

4

1 回答 1

3

正确的。问题在于您的循环条件。

feof()是邪恶的,因为它经常被误解。feof()并不表示您处于文件末尾。它仅表明它尚未遇到它(您尚未获取文件末尾之后的字节)。

当您遇到 EOF(when fgets()returns NULL) 并随后跳出循环时,您必须在循环内检测。

于 2013-11-17T23:54:58.967 回答