Hello! I need to create a book library using dynamic memory allocation and structs.
I started the program but having a hard time finishing it.. I don't really know how should i organize the program and what's missing in order to finish it.
i need to take the commends from a simulation file. and the compiling needs to be in GCC.
the simulation file looks like this:
#lines which starts with # you shall be able to ignore in your code
#1 is the add book operation id, BOOK ID, BOOK NAME,author,pages number, publish year, category
1,A250,Adventures of Huckleberry Finn,Mark Twain,120,1884,adventure
#2 operation id, book id
2,A250
#3 operation id, book id
3,A250
#4 operation id
4
#5 operation id, file name
5, C:\bookStorage.txt
#6 operation id, file name
6, C:\bookStorage.txt
explanation about each command:
1. add a book
2. delete a book
3.search a book by it's serial number
4. print out all the books
5.save the book library in a file
6. get the book library data from a file
this is what i did so far:
Code:
typedef struct{
int serial;
int pg_num;
int y_published;
char* name;
char* author;
char* category;
}Book;
typedef struct(
Book* b;
int book_num;
int length;
}Book_Shelf;
typedef struct{
int command_number;
Book b;
char* file_name;
}Command;
void set_command(command* c, char* str);
int main(int argc, char* argv[]){
FILE* pf;
char buffer[512];
Command c;
pf = fopen(argv[1], "r");
fgets(buffer, 512, pf);
while (buffer[0] == '#'){
fgets(buffer, 512, pf);
}
set_command(c, buffer);
command_execute(c);
return 0;
}
void add_book(Book_Shelf* bs, Book* b){
if (bs->book_num == bs->length){
bs->length *= 1.5;
bs->b = (Book*)realloc(bs->b, length*sizeof(Book));
if(bs->b==NULL)
exit2;
}
bs->b[book_num].serial = b->serial;
/* ... */
}
char* get_next_word(char* str, int* index){
int i, length = 0;
char* temp_str;
for (i = 0; (str[i] != ',') && (str[i] != '\0'); i++, length++);
length++;
temp_str = (char*)malloc(length);
for (i = 0; i < length; i++){
temp_str[i] = str[i];
}
temp_str[length] = '\0';
*index = i;
return temp_str;
}
void set_command(command* c, char* str){
int i = 0;
c->command_number = atoi(*(get_next_word(str+i, &i)));
switch(c->command_number){
case 1:{
c->b.serial = get_next_word(str+i, &i);
c->b.name = get_next_word(str+i, &i);
c->b.author = get_next_word(str+i, &i);
}
}
}