[英]Read the first integer in a binary file
有一个二进制文件,其中包含:
# 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
我的系统使用小字节序转换。 但其他字节仍设置为零,我看不到为什么得到此输出。
非常感谢您的解释。
您使用“ ab”选项打开文件。 Bur此选项不允许从文件读取,仅允许写入其末尾。 尝试以这种方式打开
fh = fopen(pkg_file, "w+b")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.