调用fread后直接调用fwrite写不进去,反之也是,为什么?

xiudou_123 2011-06-02 04:51:30
代码很简单,以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;
}
...全文
511 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yang_jnu 2012-06-09
  • 打赏
  • 举报
回复
同样的问题,搞了我一个多小时,原来是这样的,一直在查fopen, fwrite的文献,没想到答案在fopen,看来查文档还是非常弱呀
xiudou_123 2011-06-03
  • 打赏
  • 举报
回复
明白了,多谢大家
xiaohuh421 2011-06-02
  • 打赏
  • 举报
回复
4楼已经说到点上了
AnYidan 2011-06-02
  • 打赏
  • 举报
回复
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
就想叫yoko 2011-06-02
  • 打赏
  • 举报
回复
是缓冲区的问题
等待高手来回答了~~
xiudou_123 2011-06-02
  • 打赏
  • 举报
回复
调用ret = fread(string, 1, 10, testFile);后,文件指针不是会自动移到10个字节那里吗?
然后,我直接调用fwrite,写的内容是hello world,和读的内容不一样,怎么会不变呢?
bdmh 2011-06-02
  • 打赏
  • 举报
回复
从头读,然后又从头写,写的还是那些内容,当然不变了

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧