如何读取二进制文件!!!!!!!!!!!!!

allen828 2008-06-18 11:35:47
小弟是C++初学者,现向前辈们请教如何用标准C++读取二进制DB文件(dbfile.db),我的数据格式如下:
00 00 00 00 01 00 00 00 33 33 33 33 33 33 33 D3 3F;
01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 59 40;
02 00 00 00 03 00 00 00 72 65 70 93 1D 00 00 00 00;
....
比如读的时候如果遇到01,表示其后的数据都表示电压;如果遇到02,则表示其后的数据都表示时间;如果遇到03则表示其它...

另外请问二进制文件是不是没有行的概念?

谢谢!
...全文
127 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
飞雁 2008-06-18
  • 打赏
  • 举报
回复
FILE* pfile;

pfile=fopen(..);
fgets(...)
zwspider 2008-06-18
  • 打赏
  • 举报
回复

// 手写,不保证完全没错~~~
ifstream inFile;
inFile.open("dbfile.db", ios::in | ios::binary);
if (!inFile.is_open())
{
return EXIT_FAILURE;
}

inFile.seekg(0, ios::end);
int iFileSize = inFile.tellg();

// copy binary data to buffer, then use the data in buffer.
BYTE *pBuffer = new BYTE[iFileSize];
inFile.seekg(0, ios::beg);
inFile.read(pBuffer, iFileSize);
inFile.close();

// your code to use buffer data ...

delete []pBuffer;
return 0;
lzr4304061988012 2008-06-18
  • 打赏
  • 举报
回复
不好意思,不能用memcpy()刚才被误导了,貌视可以直接比较即if(s[0]==0x00)
lzr4304061988012 2008-06-18
  • 打赏
  • 举报
回复
char s[2];
ifstream ifs;
ifs.open("dbfile.db");
if(!ifs)
return;
while(!ifs.eof())
{
ifs.read(s,1);
if(memcmp(s[0],0x00,sizeof(s[0]))
........;
else
if(memcmp(s[0],0x01,sizeof(s[0]))
.......;
else
if..................
}
二进制有换行的概念,只不过存的是ASCII值
yuzl32 2008-06-18
  • 打赏
  • 举报
回复
大致这样?

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char fmt,buf[100];
ifstream stream("dbfile.db");

while(!stream.eof())
{
stream.get(fmt);
stream.getline(buf,100);

if(fmt == 0x0)
printf("format is 00.\n");
else if(fmt == 0x01)
printf("format is 01.\n");
else if(fmt == 0x02)
printf("format is 02.\n");
else
printf("not format.\n");

printf("the data is:%s\n",buf);
}

stream.close();

return 0;
}
allen828 2008-06-18
  • 打赏
  • 举报
回复
各位大侠我试了你们的方法,好像不行呀!可能是我没看懂你们意思..

64,684

社区成员

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

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