1. 程式人生 > >以r+方式fopen檔案,寫不進去內容

以r+方式fopen檔案,寫不進去內容

        例如下面這段程式碼:

#include<stdio.h>

int main(void)
{
	FILE* file = fopen("test.txt", "r+");

	char str[100] = {0};
	fgets(str, 100, file);
	printf(str);

	fputs("add here to test", file);

	fclose(file);
}
        編譯執行後會發現,fputs語句無效,字串無法寫入到檔案中。

        此時,在程式碼中加入一句看似沒有實際作用的語句,fputs就能向檔案中寫入內容了。

       

        fgets(str, 100, file);
	printf(str);

	fseek(file, 0, SEEK_CUR);

	fputs("add here to test", file);

原因如下,抄自MSDN:

When the "r+", "w+", or "a+" access type is specified, both reading and writing are enabled (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function.