Yes, fread and fwrite are good for that
fread(void *ptr, size_t var_size, size_t var_count, FILE *in_file);
fwrite(void *ptr, size_t var_size, size_t var_count, FILE *out_file);
So, if you have a a struct:
typedef struct Test_S
{
int x, y;
float r,z;
} ;
And you have it defined as such:
struct Test_S Testing;
you can now write it to a file:
Code: Select all
FILE *file;
file = fopen("test.bin","wb"); //wb = write binary
fwrite(&Testing,sizeof(struct Test_S),1,file);
And read it as so:
Code: Select all
FILE *file;
file = fopen("test.bin","rb"); //rb = read binary
fread(&Testing,sizeof(struct Test_S),1,file);
Just be careful when you are using pointers in a struct (like for strings!) as it will write out the pointer rather than the data it points to.
like this stuff:
Code: Select all
typedef struct Test_S
{
int x, y;
char *name;
};
It will write out x and y, and the location of the pointer of name, you would have to specifically tell it to write out the data pointed to by name by looping until it hit's a NULL. To do this is pretty simple as well, or you can use strlen to find the lenth, and pass the pointer to fwrite, but still need to read one by one until you hit a null.
Code: Select all
struct Test_S Testing;
void WriteTest_S(struct Test_S *ptr, FILE *out)
{
fwrite(ptr->x,sizeof(int),1,out);
fwrite(ptr->y,sizeof(int),1,out);
fwrite(ptr->name,strlen(ptr->name)+1,1,out); //Write it out plus 1 (for NULL)
}
void ReadTest_S(struct Test_S *ptr, FILE *in)
{
char buffer[512]; //Random buffer for now.
int len=0;
fread(ptr->x,sizeof(int),1,in);
fread(ptr->y,sizeof(int),1,out);
do{
fread(&buffer[len],sizeof(char),1,in);
++len;
} while (buffer[len-1]!=0 || len==511); //Loop while buffer[len]!=0 or we are going to overflow!
buffer[len] = 0; //If we terminated on len==511, there is no null terminator, so we add one!
name = (char*)malloc(len+1);
memcpy(ptr->name,buffer,len+1); //Copy it plus null!
}