打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
c++读写二进制文件

from 

曾经看过一个帖子http://pnig0s1992.blog.51cto.com/393390/563152,文中说c++读写二进制文件关键在于接口函数,用什么模式打开没有关系,我觉得那样讲是不对的。不过文章看一下也可以。

c++读写二进制文件,在windows与linux下可能会有不同的效果。本人写的一个小例子在linux下写入二进制数据正常,而在windows下面写入数据的过程中,竟然自动添加了0x25等等一些无意义的字节,找了好久才发现这个bug。

下面是正确的写法

  1. struct HashKey_S  
  2. {  
  3.     HashKey_S(DWORD uiFirst = 0, DWORD uiSecond = 0):uifirsthash(uiFirst), uisecondhash(uiSecond){  
  4.     }  
  5.     HashKey_S(const HashKey_S &stHash):uifirsthash(stHash.uifirsthash), uisecondhash(stHash.uisecondhash){  
  6.     }  
  7.     DWORD uifirsthash;  
  8.     DWORD uisecondhash;  
  9. };  


  1. void TestWriteBinary()  
  2. {  
  3.     const char *pcwritefile = "fileBinary.txt";  
  4.   
  5.     ofstream ofs;  
  6.     ofs.open(pcwritefile, ios::out | ios::binary);  
  7.     assert(ofs.is_open());  
  8.       
  9.     for (int i = 0; i < 100; ++i)  
  10.     {  
  11.         HashKey_S stHashKey;  
  12.         stHashKey.uifirsthash = 1;  
  13.         stHashKey.uisecondhash = 2;  
  14.         ofs.write((const char*)(&stHashKey), sizeof(stHashKey));  
  15.     }  
  16.     ofs.close();  
  17. }  

错误的写法是这样的(在linux下工作正常,windows下异常)

  1. void TestWriteBinary()  
  2. {  
  3.     const char *pcwritefile = "fileBinary.txt";  
  4.   
  5.     ofstream ofs;  
  6.     ofs.open(pcwritefile, ios::out);  
  7.     assert(ofs.is_open());  
  8.       
  9.     for (int i = 0; i < 100; ++i)  
  10.     {  
  11.         HashKey_S stHashKey;  
  12.         stHashKey.uifirsthash = 1;  
  13.         stHashKey.uisecondhash = 2;  
  14.         ofs.write((const char*)(&stHashKey), sizeof(stHashKey));  
  15.     }  
  16.     ofs.close();  
  17. }  

仅仅是在打开文件的时候,没有加ios::binary而已。


同样在读文件的同时,也一定要加上ios::binary,用read读文件即可。

下面是c++读写二进制的一些基础知识,写的不错:http://blog.csdn.net/kingstar158/article/details/6859379



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
注册表详解
小小换行符乱谈(文本文件vs二进制文件)
C ++文件流操作
C/C++输入输出流总结
C 学习笔记之对文件的操作<2>
CMap CString 做key时的解释
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服