A really basic question. About reading binary file.

wizardinred 2004-08-19 05:40:20
How can I read a particular number of records from a binary file.
For example, there is a file, whose records are like:

John 23 8888888
Mike 19 7777777
Rose 20 9999999
.
.
.
.

According to the order, they are name, age and phonenumber. Of course, they are binary records. Now, there are thousands of records in it, I just want to read three people out, how can I do? I know this is a really basic question, please help me. Thanks so much!
...全文
64 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wizardinred 2004-08-25
  • 打赏
  • 举报
回复
Thank you guys very much. Actually this is a question of my practical. The objective is just test whether we can understand C++ read binary file depending on bytes. Anyway, you guys have given me a really nice answer, thanks again.
ma100 2004-08-19
  • 打赏
  • 举报
回复
同意whyglinux(山青水秀)
读的时候 可以用
FILE *fp=fopen("path","r+b");
long n;//第n条record
struct Record record;
fseek(fp, n*sizeof(struct Record),SEEK_SET);
fread(&record,sizeof(struct Record),1,fp);
fclose(fp);
whyglinux 2004-08-19
  • 打赏
  • 举报
回复
如果你不知道一个记录(如 John 23 8888888 就是一个记录)的具体结构的话,你无法实现你的想法。

一个记录可以用如下的结构体来表示:

struct Record {
char name[num]; // 你要事先知道 num 是多少。
int age; // 你要事先知道 age 的类型是否是 int 还是其它类型
long others; // 你要事先知道 others 的类型是什么,不一定是 long。
};

弄清楚记录的结构之后就好办了,就可以用文件操作函数一个记录一个记录地读出来了。
wizardinred 2004-08-19
  • 打赏
  • 举报
回复
Such a piece of cake, please help me.
So sorry for writing in English, because the computer I am using now only has English OS.

64,654

社区成员

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

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