C++读写二进制文件的问题

McAjay 2009-05-01 08:09:57
程序部分代码如下:
map<string,char*>::iterator iter;
//char* temp=new char[33];
while(!fin.eof()){
char* temp=new char[33];
fin.read(temp,32);
temp[32]='\0';
hash=temp;
iter=data_map.find(hash);
if(iter!=data_map.end()) {
fout<<iter->second;
//cout<<iter->first<<endl;
//cout<<iter->second<<endl;
}
else break;
}
fout.close();
就是想从一个文件中读一段32字节的长度的数据为后续操作作准备,但是对于二进制文件
,这段代码运行的结果是错误的,请问问题出现的原因以及应该如何修改?O(∩_∩)O谢谢
...全文
114 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
McAjay 2009-05-03
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 goodname 的回复:]
问题应该是出在
hash = temp;
如果temp中出现'\0'就会被截断

你可以使用hash.assign(temp,32);
当然你也要确保data_map里面的正确性
[/Quote]
谢了~~~确实是这样的
之前我自己的解决方法是:
stringstream ss;
ss.write(temp,32);
hash=ss.str();

不过你的方法显然简洁多了O(∩_∩)O~
goodname 2009-05-01
  • 打赏
  • 举报
回复
问题应该是出在
hash = temp;
如果temp中出现'\0'就会被截断

你可以使用hash.assign(temp,32);
当然你也要确保data_map里面的正确性
Cpp权哥 2009-05-01
  • 打赏
  • 举报
回复
open的时候就要用ios::in|ios::binary指明二进制格式。
Kevin_Perkins 2009-05-01
  • 打赏
  • 举报
回复

map <string,char*>::iterator iter;
char* temp=new char[33];
fin.open("C:\\test", ios::in || ios::binary);
while (!fin.eof()) {
fin.read(temp, 32);
temp[32]='\0';
hash = temp;
iter = data_map.find(hash);
if (iter != data_map.end()) {
fout < <iter->second;
//cout < <iter->first < <endl;
//cout < <iter->second < <endl;
}
else
break;
}
fout.close();

McAjay 2009-05-01
  • 打赏
  • 举报
回复
上面给出的知识部分代码,前面打开文件的时候用的是ios::binary模式,全部代码如下:
void DataManager::MergeFile(char *file_namer,char* file_namew){//将数据块还原成文件
LoadMap(file_namer);
fstream fin("FileHash.hash",ios_base::binary|ios_base::in);
fstream fout(file_namew,ios_base::binary|ios_base::out);
string hash;
int block_id=0;

map<string,char*>::iterator iter;
char* temp=new char[32];
while(!fin.eof()){
//char* temp=new char[32];
fin.read(temp,32);
//temp[32]='\0';
fin.write(temp,32);
hash=temp;
iter=data_map.find(hash);
if(iter!=data_map.end()) {
fout<<iter->second;
//cout<<iter->first<<endl;
//cout<<iter->second<<endl;
}
else break;
}
fout.close();
}
jn989 2009-05-01
  • 打赏
  • 举报
回复
好像是要用ios::binary 吧
lz看看这个:
http://blog.tanggaowei.com/2008/05/c-2.html
liliangbao 2009-05-01
  • 打赏
  • 举报
回复
帮顶~

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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