在下面的代碼中,我正在搜索'。'在我的模板後面粘貼一個字符串。出於某種原因,雖然字符串按預期粘貼,但會從我的模板中刪除一些文本。我不知道問題出在哪裏。試過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
這就好像你認爲'fputs' _inserts_內容到一個文件中。它不;它只是覆蓋當前存在的任何東西(在當前位置)。 – davmac
它不會「刪除」,它只是用新的覆蓋你現有的數據。如果你想插入,你需要自己做。 – Matt
Ii可能會覆蓋數據。當你使用'r +'模式時,它不會刪除任何已經存在的數據。所以看看你是否正確定位光標。 – ameyCU