Hey! I am currently doing some prep for my upcoming college assignment but am facing some difficulties.
I have to write an C database application that will store book details into a file, and allow me to recall them and delete them. I am having some problem with reading the file, the entries just won’t show when I list them all (Option 3).
I have had a look at the database file so I think it has been written to correctly.
Here is the basic function of my code:
#include<stdio.h>
#include <stdlib.h>
// Global Varables
FILE *fp, *ft;
// Structs
typedef struct Books
{
int id;
char title[25];
char forename[25];
char surname[25];
char isbn[13];
}Books;
void displayMenu()
{
printf("Options");
}
void runapp()
{
int option;
char isbn[20];
char deleteOrNot[2];
Books book;
fp = fopen("database.dat", "a+");
if (fp == NULL)
{
printf("Failed to open file.");
}
long int booksize = sizeof(book);
do
{
displayMenu();
printf("Enter menu option: ");
scanf("%i", &option);
switch(option)
{
// =================================================================
// -------- OPTION 1: Add a new book
// =================================================================
case 1:
fseek(fp, 0, SEEK_END);
printf("Please enter the books title: ");
scanf("%s", book.title);
printf("Please enter the authors first name: ");
scanf("%s", book.forename);
printf("Please enter the authors surname: ");
scanf("%s", book.surname);
printf("Please enter the ISBN number: ");
scanf("%s", book.isbn);
fwrite(&book, booksize, 1, fp);
fflush(stdin);
break;
// =================================================================
// -------- OPTION 2: Search and delete
// =================================================================
case 2:
// Search and delete
break;
// =================================================================
// -------- OPTION 3: List all books
// =================================================================
case 3:
rewind(fp);
while(fread(&book, booksize,1, fp))
printf("%s", book.title);
printf("\n\nPress any key to return to menu.");
getch();
break;
// =================================================================
// -------- OPTION 4: Exit the application
// =================================================================
case 4:
fclose(fp);
exit(0);
break;
}
if (system("cls")) system("clear");
}while(option != "\n");
}
int main()
{
runapp();
return 0;
}
Any help with solving this problem would be great!
Also feel free to give me some tips on my code.
You’re trying to write the
bookstructure directly to and from the file rather than a textual representation of the data, so you need to open the file in binary mode, (addbto thea+in thefopencall). Otherwise your data could be slightly corrupted as the i/o library tries to translate carriage returns and line feeds to and from your host computer’s preferred convention.