2015-09-25 53 views
2

在下面的代码中,我正在搜索'。'在我的模板后面粘贴一个字符串。出于某种原因,虽然字符串按预期粘贴,但会从我的模板中删除一些文本。我不知道问题出在哪里。试过fflush()没有什么好效果。
在C中的文件读写模式“r +”意外行为

#include <stdio.h> 
#include <string.h> 

int main() { 
    FILE * fp; 
    int tmp_char, tmp_offset; 
    char file_name[50] = "FileIoTest_template.txt"; 
    char tmp_string1[50] = "Generic String 1"; 
    char tmp_string2[50] = "Generic String 2"; 
    long tmp_long; 

    fp = fopen(file_name, "r+"); 
    //fseek(fp, 0, SEEK_SET); 

    do { 
     tmp_char = fgetc(fp); 
     printf("%c ", tmp_char); 
     if (tmp_char == '.') 
      break; 
    } while (tmp_char != EOF); 
    tmp_long = ftell(fp); 
    fseek(fp, tmp_long, SEEK_SET); 
    tmp_offset = strlen(tmp_string1); 
    fputs(tmp_string1, fp); 
    fputs("\n", fp); 
    //fflush(fp); 

    fseek(fp, tmp_long+tmp_offset, SEEK_SET); 
    do { 
     tmp_char = fgetc(fp); 
     printf("%c ", tmp_char); 
     if (tmp_char == '.') 
      break; 
    } while (tmp_char != EOF); 
    tmp_long = ftell(fp); 
    fseek(fp, tmp_long, SEEK_SET); 
    fputs(tmp_string2, fp); 
    fputs("\n", fp); 
    //fflush(fp); 

    fclose(fp); 
    return 0; 
} 

这里是我的模板 “FileIoTest_template.txt”:

Sample list: 
1. 
2. 
3. 
random text 

4. 
5. 
6. 

bunch of random text 

我的代码的输出是:

Sample list: 
1.Generic String 1 
ext 

4.Generic String 2 
of random text 
+3

这就好像你认为'fputs' _inserts_内容到一个文件中。它不;它只是覆盖当前存在的任何东西(在当前位置)。 – davmac

+0

它不会“删除”,它只是用新的覆盖你现有的数据。如果你想插入,你需要自己做。 – Matt

+0

Ii可能会覆盖数据。当你使用'r +'模式时,它不会删除任何已经存在的数据。所以看看你是否正确定位光标。 – ameyCU

回答

2

你不能简单的通过将数据修改文件在它的中间没有替换任何已经存在的东西。您需要覆盖整个文件,从插入点到结尾(通过原始端到新端需要的任何点)。正确地做到这一点非常棘手,而且尝试是不安全的,因为如果过程在中间被中断,那么文件就会被丢弃。

通常,在临时文件中创建一个新版本的文件内容,一旦成功完成,就用新文件替换原始文件。

+0

谢谢。我的错误是假定文件写入操作插入文本,事后看起来很愚蠢。 –