以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.

猜你喜欢

转载自blog.csdn.net/missgya/article/details/74828700