1

I'm trying to create a small book library in C so I wrote a function that insert a book by it's name, id and quantity. For some reason the program is ruining fine and the function seems to be working but the external file remain unchanged (no new data is added). I checked the path of the file but still the problem persist. how can I fix this?

here's the function and the structure:

struct library{
int id;
int qty;
char name[50];
};
void InsertBook()
{
    struct library b;
    FILE *books;
    if((books=fopen("C:\\mybooks.txt","a+")==NULL))
    {
        printf("file not found\n");
    }
    else
    {
        printf("You will need to enter a name, ID, and quantity of the book.\n");
        printf("please enter book name:");
        fflush(stdin);
        fgets(b.name,SIZE,stdin);
        fputs(b.name,books);
        printf("please enter book ID:");
        scanf("%d",&b.id);
        printf("please enter book quantity:");
        scanf("%d",&b.qty);
        fprintf(books,"%d %s %d\n",b.name,b.id,b.qty);
        fclose(books);
    }
}```

2 Answers2

0

The only mistake you've done is:

fprintf(books, "%d %s %d\n", b.name, b.id, b.qty);

Just do:

fprintf(books, "%s %d %d\n", b.name, b.id, b.qty); // %s before %d

And everything's OK.

Side Tips

  • fputs() not required here.
  • books = fopen("C:\\mybooks.txt", "a+") == NULL expression won't work for most compilers because the assignment makes pointer from integer without a cast.

    Instead you can assign it before comparing it to the null expression as shown:

    books = fopen("C:\\mybooks.txt", "a+");
    if (books == NULL) { ... }```
    

Important note: Ensure you have writing permission in that destination.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
0

The program does work (but see errors below), however you are writing to the root folder of Drive C. The output file is visible from a console, but not from Windows file explorer. Normally, you should not use the root folder of C drive.

There is a parenthesis in the wrong place here

if((books=fopen("mybooks.txt","a+")==NULL))

which should be

if((books = fopen("mybooks.txt","a+")) == NULL)

There are wrong format specifications wrong in fprintf here, as complained by the compiler

fprintf(books,"%d %s %d\n",b.name,b.id,b.qty);

should be

fprintf(books, "%s %d %d\n", b.name, b.id, b.qty);

You unnecessarily duplicate writing the book title to file a few lines above with

fputs(b.name,books);

You use an incorrect buffer size for fgets here

fgets(b.name,SIZE,stdin);

which should be

fgets(b.name, sizeof b.name, stdin);

Also, you must check the return values particularly from user input functions such as fgets and scanf.


Additionally there are faults waiting to happen with the input of the book title here
fgets(b.name, sizeof b.name, stdin);

So I suggest you replace that line with

if(scanf("%49[^\n]", b.name) != 1)
    exit(1);

It is best not to mix the input methods: stick to one.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56