使用fwrite和fread与文件的问题。 [英] Problem using fwrite and fread with files.

查看:77
本文介绍了使用fwrite和fread与文件的问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这个代码在Visual C ++ 2010 Express中给我带来了问题。如果编译并在Ubuntu中使用gcc执行它,我就没有这个问题:



So this the code which is giving me problem in Visual C++ 2010 Express. I don''t have this problem if a compile it and execute it with gcc in Ubuntu:

FILE * pFile;
char buffer[] = { ''x'' , ''y'' , ''z'' };

pFile = fopen ( "myfile.bin" , "wb" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fread(buffer,1,sizeof(buffer),pFile);

printf("%c,%c,%c",buffer[0],buffer[1],buffer[2]);





问题是每当我尝试使用fwrite函数写入文件时它会写入垃圾字符。

因为当我尝试使用fread和它来检索它们时我用printf打印它们,缓冲区的内容已更改为''=''。



即使我将文件模式设置为w并打开带有记事本的文件我看到它正确但文件末尾有垃圾字符。

所以我不知道为什么会这样。

是我从这里复制了这个确切的例子它应该工作正常。



http://www.cplusplus.com/reference/cstdio/fwrite/ [ ^ ]

推荐答案

您的程序不正确。为了读取写入的数据,您必须(重新)将文件指针放在文件的最开头。这可以通过关闭文件然后再次打开以进行阅读来完成。

You program is incorrect. In order to read the written data, you have to (re)position the ''file pointer'' at the very beginning of the file. This can simply accomplished by closing the file and then open it again for reading.
//...
pFile = fopen ( "myfile.bin" , "wb" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fclose(pFile);
fopen ( "myfile.bin" , "rb" );
fread(buffer,1,sizeof(buffer),pFile);
//...







顺便说一下:你应该经常检查被调用函数的返回值。




By the way: you should always check the return value of the called functions.


这篇关于使用fwrite和fread与文件的问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆