读书人

调用fread后直接调用fwrite写不进去

发布时间: 2012-06-09 17:16:42 作者: rapoo

调用fread后直接调用fwrite写不进去,反之也是,为什么?
代码很简单,以rb+形式打开一个已存在的文件(文件内容是abcdefghijklmnopqrstuvwxyz
),然后随便读几个字节,然后直接调fwrite,返回值是正确的,但是fclose后,双击打开文件,文件内容没变。
反之,以rb+形式打开一个已存在的文件(文件内容也是abcdefghijklmnopqrstuvwxyz
),随便写几个字节(写了hello world),然后直接调fread,只读出了??????????,而且fclose后,双击打开文件,文件内容变成hello world??????????vwxyz

但是在fread和fwrite之间调一下fseek,读写内容就都对了。请问高手,这为什么呢?fread和fwrite为什么不能连续调用?
具体代码如下:

int _tmain(int argc, _TCHAR* argv[])
{
FILE *testFile = NULL;
int ret = 0;
char string[200] = {'\0'};

testFile=fopen("test1.txt", "rb+"); //test1.txt的内容是abcdefghijklmnopqrstuvwxyz
if(testFile == NULL)
{
return 0;
}
ret = fread(string, 1, 10, testFile);
//ret = fseek(testFile, 0, SEEK_CUR);
ret = fwrite("hello world", 1, 11, testFile);
fclose(testFile); //test1.txt的内容还是abcdefghijklmnopqrstuvwxyz
//如果fread和fwrite之间调用了fseek,文件内容变成abcdefghijhello worldvwxyz

testFile=fopen("test2.txt", "rb+"); //test2.txt的内容也是abcdefghijklmnopqrstuvwxyz

if(testFile == NULL)
{
return 0;
}
ret = fwrite("hello world", 1, 11, testFile);
//ret = fseek(testFile, 0, SEEK_CUR);
ret = fread(string, 1, 10, testFile);
fclose(testFile); //test2.txt的内容变成hello world??????????vwxyz
//如果fread和fwrite之间调用了fseek,文件内容变成hello worldlmnopqrstuvwxyz

return 0;
}

[解决办法]
FILE *fopen(const char *filename, const char *mode)
fopen opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode include:
"r"
open text file for reading
"w"
create text file for writing; discard previous contents if any
"a"
append; open or create text file for writing at end of file
"r+"
open text file for update (i.e., reading and writing)
"w+"
create text file for update, discard previous contents if any
"a+"
append; open or create text file for update, writing at end
Update mode permits reading and writing the same file; fflush or a file-positioning function must be called between a read and a write or vice versa. If the mode includes b after the initial letter, as in "rb" or "w+b", that indicates a binary file. Filenames are limited to FILENAME_MAX characters. At most FOPEN_MAX files may be open at once.

the c programming language - 221

读书人网 >C语言

热点推荐