免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: jmy2446267
打印 上一主题 下一主题

[算法] 复杂数据的文件读写问题 [复制链接]

论坛徽章:
0
11 [报告]
发表于 2008-10-09 20:38 |只看该作者
原帖由 prc 于 2008-10-9 18:50 发表

这个说法有根据吗?

不明白,我只知道fread/fwrite是C标准库中的函数,语义也很清楚,支持标准库函数的系统应该都能用

论坛徽章:
0
12 [报告]
发表于 2008-10-09 21:09 |只看该作者
A fundamental problem with binary I/O is that it can be used to read only data that has been written on the same system. This was OK many years ago, when all the UNIX systems were PDP-11s, but the norm today is to have heterogeneous systems connected together with networks. It is common to want to write data on one system and process it on another. These two functions won't work, for two reasons.

1. The offset of a member within a structure can differ between compilers and systems, because of different alignment requirements. Indeed, some compilers have an option allowing structures to be packed tightly, to save space with a possible runtime performance penalty, or aligned accurately, to optimize runtime access of each member. This means that even on a single system, the binary layout of a structure can differ, depending on compiler options.

2. The binary formats used to store multibyte integers and floating-point values differ among machine architectures.

We'll touch on some of these issues when we discuss sockets in Chapter 16. The real solution for exchanging binary data among different systems is to use a higher-level protocol. Refer to Section 8.2 of Rago [1993] or Section 5.18 of Stevens, Fenner, & Rudoff [2004] for a description of some techniques various network protocols use to exchange binary data.


From APUE Chapter 5 Standard I/O Library

一般来说,这不是一个问题,因为我们只是在同一台机器上写入,以后再读取出来。。。

论坛徽章:
0
13 [报告]
发表于 2008-10-10 12:29 |只看该作者
我的做法是这样地
对于包含别struct的struct,老老实实一个个字段写
对于不包含其它struct的struct,就直接整个输出

struct b
{
  int var;
};

struct a
{
  int var;
  struct b* s;
};

struct b sb;
struct a sa;
sa.s=&sb;

//write
fopen("filename","wb");
fwrite( &(sa.var), sizeof(int), 1, fd);
fwrite( sa.s, sizeof(struct b), 1, fd);
fclose(fd);

//read
fopen("filename","rb");
fread( &(sa.var), sizeof(int), 1, fd);
fread( sa.s, sizeof(struct b), 1, fd);
fclose(fd);

供楼主参考。。。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP