我有一些二进制文件,我写结构对象(一个定义的类型)。我希望能读懂特别的(英文)。"结构块"从一个二进制文件转换成一个结构体并显示它。我想到的唯一的想法是创建一个包含所有这些结构的数组,这样我就可以访问普通的结构,但这似乎不是一个有效的方法。如果有人能帮我解决这个问题,我将不胜感激。
我是C的新手,但我想我可以帮上忙。这是你想要做的事情吗?
#include<stdio.h>
#include<stdlib.h>
//just a struct for purposes of demonstration
struct my_struct{
int prop1;
int prop2;
};
//writes structs to filename.dat
void writeStruct(int property){
FILE *file_pointer;
file_pointer = fopen("filename.dat","ab");
//define and assign variables to a quick dummy struct
struct my_struct this_struct;
this_struct.prop1=property;
this_struct.prop2=property*2;
//write struct to file
fwrite(&this_struct, sizeof(this_struct), 1, file_pointer);
fclose(file_pointer);
}
//returns the nth struct stored in "filename.dat"
struct my_struct getNthStruct(long int n){
FILE *file_pointer;
file_pointer = fopen("filename.dat","rb");
//will be the struct we retrieve from the file
struct my_struct nth_struct;
//set read position of file to nth struct instance in file
fseek(file_pointer, n*sizeof(struct my_struct), SEEK_SET);
//copy specified struct instance to the 'nth_struct' variable
fread(&nth_struct, sizeof(struct my_struct), 1, file_pointer);
return nth_struct;
}
int main(){
//write a bunch of structs to a file
writeStruct(1);
writeStruct(2);
writeStruct(3);
writeStruct(4);
writeStruct(5);
//get nth struct (2 is third struct, in this case)
struct my_struct nth_struct;
nth_struct=getNthStruct(2);
printf("nth_struct.prop1=%d, nth_struct.prop2=%dn",
nth_struct.prop1, //outputs 3
nth_struct.prop2); //outputs 6
return 0;
}
为了简洁和隔离核心概念,我故意没有检查明显的错误(文件指针返回NULL
,文件长度等)。
欢迎反馈