使用fwrite和fread与文件的问题。

编程入门 行业动态 更新时间:2024-10-26 17:28:47
本文介绍了使用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并打开带有记事本的文件我看到它正确但文件末尾有垃圾字符。 所以我不知道为什么会这样。 是我从这里复制了这个确切的例子它应该工作正常。 www.cplusplus/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与文件的问题。

本文发布于:2023-08-05 11:20:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1305198.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   fwrite   fread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!