Stop being the product.
Become the owner.
or
sign uplog in

Need help with a C program Hi, I'm making a library…

Need help with a C program

Hi, I'm making a library management program that takes in a book's characteristics (ISBN, author, year published, etc.), stores it in an array of structs and stores this into a file.

Here it is:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct book
{
char ISBN[20];
char title[100];
int accno;
int year;
char genre[50];
char authname[100];
int issued;
};

struct book *bookArray;
int a = 0;
void readFile()
{

FILE *fp;
fp = fopen("db.txt", "r+");
if(!fp)
{
perror("fopen");
return;
}

if(fp != NULL)
{
fread(bookArray, sizeof(struct book), 1, fp);
}
}

void write()
{
FILE *fp;
fp = fopen("db.txt", "a+");
fwrite(bookArray, sizeof(struct book), 1, fp);
fclose(fp);
}

void addBook(struct book b)
{
bookArray[a++] = b;
}

int main()
{
bookArray = malloc(sizeof(struct book));
struct book b = {"0-394-49219-6", "Tinker, Sailor, Soldier, Spy", 1, 1974, "spy fiction", "Le Carre", 0};
bookArray[0] = b;
addBook(b);
write();
readFile();

for(int i = 0; i < a; i++)
{
printf("%s\t%s\t%d\t%d\t%s\t%s\t%d\n", bookArray[i].ISBN, bookArray[i].title, bookArray[i].accno, bookArray[i].year, bookArray[i].genre, bookArray[i].authname, bookArray[i].issued);
}
}

1. I'm not able to figure out how to store the value of ```a``` after the program exits. I thought of storing it in another file, but was wondering if there's a better way to do that.

2. How do I allocate dynamically increasing space (as the number of books increase) to ```bookArray```? I get only only one row printed from the loop if I run the program several times, despite ```db.txt``` storing all the runs.

I'm posting here for the first time and I hope I haven't violated any rules.

Thanks in advance!
#dev #technology #programming
earnings
2,000 mlx total
$0  total
engagement
2 views
0 reactions

0 comments