I have created this programming problem where I read list of books from a binary file into array of structs. If the file does not exist, then I want the program to create the file.
In this case, I ask the user to enter the books and their authors. Then I write this to the file as series of structs.
If the file already exists with some books (with authors) on it, I want to give an option to the user to either keep, delete or update the book entry of the file.
And if the user deletes some books, then user should be given option to enter number of books as long as some limit (MAX BOOKS) is not reached.
I am confused as to which mode should I use to open the file using fopen
.
If r+b
mode is used, then there will be an error if the file doesn't exist.
If a+b
mode is used then writing can only be appended. So, if the user has decided to delete some books, and enter other books, this information will be be sequentially appended to the file.
How can this problem be approached ?
I found a solution to this problem using nested fopen
calls in different modes.
If pbooks
is the FILE pointer to the binary file called book.dat
. Then I did the following
FILE * pbooks;
if ((pbooks = fopen("book.dat", "r+b")) == NULL)
{
if ((pbooks = fopen("book.dat", "w+b")) == NULL)
{
exit(EXIT_FAILURE);
}
}
So, initially, if the file doesn't exist, initial fopen function returns NULL
and so inner fopen statement is executed and the file is created. When the file is already created and the program is executed again, initial fopen function is executed successfully and since the mode is r+b
, the existing file is not truncated, so that we have access to the data which was entered earlier. I tested this and this is working. Please comment if this approach is recommended in practice.