Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a structure containing a string into a binary file

I have a binary file where I log the offset at which writes to other files occur and the data that is written at that offset. Now I define the structure of each log record as

struct log_record{
                    int offset;
                    char *data;
               }
struct log_record t;

When I write the record into the file, I have the length of data that I write into the file and hence before assigning I allocate space as

t.data = (char*)malloc(sizeof(char)*strlen(buff));/*buf holds the data to be written*/

Now I have the length of the record I am writing into the file...But the issue is while reading. How do I allocate space against a structure that I read the record into and in the fread what should be the size of the record. Am a few confused. Would be gratefull for help

like image 909
Lipika Deka Avatar asked Dec 02 '25 04:12

Lipika Deka


1 Answers

You need to write the length of the string as the length of string is variable.

Note that strlen() doesn't return the size including the terminating NULL.

EDIT + EDIT 2 (thanks to mu is too short) + EDIT 3 (thanks to mu is too short)

This is how I'd do it:

t.data = (char*) malloc(sizeof(char) * strlen(buff) + 1);
strcpy(t.data, buff);

// ...
int data_size = strlen(t.data) + 1;
fwrite(&t.offset,  1, sizeof(t.offset),   file);
fwrite(&data_size, 1, sizeof(data_size),  file);
fwrite(t.data,     1, strlen(t.data) + 1, file);
like image 52
Donotalo Avatar answered Dec 03 '25 19:12

Donotalo