I'm building a library program that keeps books in an array of structs and writes them to a file. How can I recover the number of books when the program restarts, and grow the array as books are added?
How should I store and grow a book array in C?
Answers
Keep two separate values: the number of books currently stored and the array's capacity. Allocate capacity times sizeof(struct book), then check whether the array is full before adding a book.
When it fills up, increase the capacity in blocks or double it with realloc. Assign realloc's result to a temporary pointer first. If allocation fails, the original array is still available. Also check for size overflow before calculating the allocation size, and free the array when you're done.
Your current allocation has room for just one book. Setting element zero and then adding a book also writes to element zero while the count is still zero, so decide whether that initial assignment should count as an addition.
Reply to this answer
If the file contains only complete, fixed-size struct records, you can seek to the end, get its size with ftell, and divide by sizeof(struct book) to find the count. Check for seek and tell errors, and treat a remainder as a damaged or incomplete record.
Another option is to read records one at a time and increment the count for each successful read. That works nicely with a growing array and avoids needing a separate count file.
Reply to this answer
Writing whole structs directly is convenient for a quick experiment, but it isn't a portable file format. Padding, integer representation and field layout can differ across builds or machines. For a durable file, define how each field is encoded, such as a text format with clear rules for separators and escaping.
Reply to this answer
Pick one storage strategy and make the read and write operations match it. You could load all records at startup, modify the array, then overwrite the file with the whole array when saving. Or append only new records as they are added.
Right now the write appends just one struct, and the read loads just one struct over the beginning of the array. Neither operation uses the book count. Check fopen, fread and fwrite results, close the file after reading too, and use binary modes for binary struct data.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Moxby.7t:
That count calculation assumes the same struct representation is used to read the file as was used to write it.