由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - fread/fwrite有big/small endian问题吗?
相关主题
serialization 到底该怎么理解啊?ask a question about struct in C programming
有没有现成的模拟fread的bufferRead()?一个popen加gzip的问题
How difficult is it to write your own sprintf ?C语言,结构体转字符串。简单的难题
c的文件写入问题怎样读一个不断更新的文件
a linux disk IO question (转载)gcc 编译的时候要包括 header source file 吗?
请教一个C的问题VC++里一个函数有参数[out]LPWSTR p要不要初始化?
c++如何把小数转成二进制输出到文本文件?c的问题(2)
size of structure请教如何通过FILE指针删除文件?
相关话题的讨论汇总
话题: fread话题: nbr话题: endian话题: file话题: fwrite
进入Programming版参与讨论
1 (共1页)
g*********s
发帖数: 1782
1
For example:
big endian machine,fwrite(&x, sizeof(int), 1, output).
small endian machine, fread(&y, sizeof(int), 1, input).
Here input and output point to the same file.
Will fread/write transparently handle this issue?
t****t
发帖数: 6806
2
of course not. you need to handle it.

【在 g*********s 的大作中提到】
: For example:
: big endian machine,fwrite(&x, sizeof(int), 1, output).
: small endian machine, fread(&y, sizeof(int), 1, input).
: Here input and output point to the same file.
: Will fread/write transparently handle this issue?

b******n
发帖数: 592
3
no, it won't. you need to handle it correctly

【在 g*********s 的大作中提到】
: For example:
: big endian machine,fwrite(&x, sizeof(int), 1, output).
: small endian machine, fread(&y, sizeof(int), 1, input).
: Here input and output point to the same file.
: Will fread/write transparently handle this issue?

i*****f
发帖数: 578
4
GNU libc has an socket API handles this because tcp packet and x86 machine
uses different endians. I remember it is ntol() or lton().

【在 g*********s 的大作中提到】
: For example:
: big endian machine,fwrite(&x, sizeof(int), 1, output).
: small endian machine, fread(&y, sizeof(int), 1, input).
: Here input and output point to the same file.
: Will fread/write transparently handle this issue?

l***i
发帖数: 1309
5
Here is one way to handle it.
#include
#include
#include
size_t write_uint32_to_file( FILE* file, uint32_t nbr )
{
nbr = htonl( nbr ); // Host to network long
return fwrite( file, &nbr, 4, 1 );
}
size_t read_uint32_from_file( FILE* file, uint32_t* nbr )
{
size_t res = fread( file, nbr, 4, 1 );
*nbr = ntohl( *nbr ); // Network to host long
return res;
}

【在 g*********s 的大作中提到】
: For example:
: big endian machine,fwrite(&x, sizeof(int), 1, output).
: small endian machine, fread(&y, sizeof(int), 1, input).
: Here input and output point to the same file.
: Will fread/write transparently handle this issue?

1 (共1页)
进入Programming版参与讨论
相关主题
请教如何通过FILE指针删除文件?a linux disk IO question (转载)
help: 一个很简单的 PayPal API 总是报错; PayPal alternative请教一个C的问题
一道面试题c++如何把小数转成二进制输出到文本文件?
C问题,被64bit iPhone搞晕了size of structure
serialization 到底该怎么理解啊?ask a question about struct in C programming
有没有现成的模拟fread的bufferRead()?一个popen加gzip的问题
How difficult is it to write your own sprintf ?C语言,结构体转字符串。简单的难题
c的文件写入问题怎样读一个不断更新的文件
相关话题的讨论汇总
话题: fread话题: nbr话题: endian话题: file话题: fwrite