The char * field of your structure is known as a variable-length field. When you write this field, you will need a method for determining the length of the text. Two popular methods:
1. Letter size first
2. Recording a terminal symbol
Writing the first size
In this method, the size of the text data is written first, then the data immediately.
Advantages: text can load faster with block reading.
Disadvantages: two readings required, additional space for data length.
Example code snippet:
struct My_Struct { char * text_field; }; void Write_Text_Field(struct My_Struct * p_struct, FILE * output) { size_t text_length = strlen(p_struct->text_field); fprintf(output, "%d\n", text_length); fprintf(output, "%s", p_struct->text_field); return; } void Read_Text_Field(struct My_STruct * p_struct, FILE * input) { size_t text_length = 0; char * p_text = NULL; fscanf(input, "%d", &text_length); p_text = (char *) malloc(text_length + sizeof('\0')); if (p_text) { fread(p_text, 1, text_length, input); p_text[text_length] = '\0'; } }
Writing a terminal character In this method, text data is written, followed by the "end" character. Very similar to the C language string. Advantages: Requires less space than Size First. Disadvantages: the text must be read one byte at a time, so the terminal character is not skipped.
Fixed size field
Instead of using char* as a member, use char [N] , where N is the maximum size of the field. Advantages: Fixed-size records can be read as blocks. Makes random access to files easier. Disadvantages: Space waste if the entire field space is not used. Problems when the field size is too small.
When writing data structures to a file, you should consider using a database . There are smaller ones like SQLite and larger ones like MySQL. Do not waste time writing and debugging persistent storage programs when they have already been written and tested.