Reputation: 41
I have some binary file that i write struct objects to(of one defined type). I want to be able to read particular (ith) "struct block" from a binary file to a struct and display it. The only idea that comes to my mind is to create an array of structures containning all of them so that i could have an access to the ordinary one but it doesn't seem to be an efficient way. I would appreciate if one could help me with this problem :)
Upvotes: 1
Views: 454
Reputation: 7225
I am new to C but think I can help with this. Is this the kind of thing you were looking to do:
#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=%d\n",
nth_struct.prop1, //outputs 3
nth_struct.prop2); //outputs 6
return 0;
}
I intentionally didn't check for obvious errors (FILE pointers returning NULL
, length of files, etc) for brevity and isolating the core concept.
Feedback is welcome.
Upvotes: 3