读取二进制文件中的第一个整数
拥有一个包含以下内容的二进制文件:
# hexdump file.pak
0000000 09 00 00 00
0000004
尝试使用 fread 读取它会导致:
int main(void){
char *filename = "file";
FILE *fh = header_open(filename);
header_init(fh);
header_read_num_files(fh);
header_close(fh);
}
FILE *header_open(char *pkg_file){
FILE *fh;
// open file with binary/read mode
if ( (fh = fopen(pkg_file, "ab")) == NULL){
perror("fopen");
return NULL; // todo: ...
}
return fh;
}
int header_read_num_files(FILE *fh){
fseek(fh, 0L, SEEK_SET);
char c;
fread(&c, sizeof(char), 1, fh);
fprintf(stderr,"buff received: %d\n", c);
}
/* write first 0 for number of files */
void header_init(FILE *fh){
unsigned int x= 9;
fseek(fh, 0, SEEK_SET);
fwrite( (const void*)&x, sizeof(int), 1, fh);
}
output: buff received: 112
我的系统使用小字节序转换。但其他字节仍然设置为零,我真的不明白为什么我会得到这个输出。
非常感谢您的解释。
Having a binary file that holds:
# hexdump file.pak
0000000 09 00 00 00
0000004
trying to read it with fread results in :
int main(void){
char *filename = "file";
FILE *fh = header_open(filename);
header_init(fh);
header_read_num_files(fh);
header_close(fh);
}
FILE *header_open(char *pkg_file){
FILE *fh;
// open file with binary/read mode
if ( (fh = fopen(pkg_file, "ab")) == NULL){
perror("fopen");
return NULL; // todo: ...
}
return fh;
}
int header_read_num_files(FILE *fh){
fseek(fh, 0L, SEEK_SET);
char c;
fread(&c, sizeof(char), 1, fh);
fprintf(stderr,"buff received: %d\n", c);
}
/* write first 0 for number of files */
void header_init(FILE *fh){
unsigned int x= 9;
fseek(fh, 0, SEEK_SET);
fwrite( (const void*)&x, sizeof(int), 1, fh);
}
output: buff received: 112
My system uses the small-endianness conversion. but still the other bytes are set to zero, I cannot really see why I'm getting this output.
An explanation is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用“ab”选项打开文件。但此选项不允许从文件中读取,只允许写入文件末尾。尝试用这种方式打开
You open the file with "ab" option. Bur this option does not allow to read from file, only writing to its end is alloowed. Try to open this way