SOURCE ::
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h> // strcmp()
#define MAX 255
struct book {
int Book_ID;
char* Title;
char* Publisher;
char* Author;
int Price;
} book_db;
int main(int argc, char *argv[])
{
char cBuf[MAX];
int fd, id;
char c;
if (argc < 2) {
fprintf(stderr, "manual : %s file_name\n", argv[0]);
}
if ((fd = open(argv[1], O_WRONLY|O_CREAT|O_EXCL, 0640)) == -1) {
perror(argv[1]);
}
while(1) {
int number;
printf("\nThis is Seong-Jae Database Book Management System\n");
printf("1. Add book\n");
printf("2. Update book\n");
printf("3. Find book\n");
printf("4. Exit\n");
printf(">> ");
fgets(cBuf, MAX, stdin);
if(strncmp(cBuf, "1", 1) == 0){
printf("%-9s %-15s %-15s %-10s %-10s\n", "Book_ID","Title", "Publisher", "Author", "Price");
scanf("%d %s %s %s %d", &book_db.Book_ID, book_db.Title, book_db.Publisher, book_db.Author, &book_db.Price) == 5;
lseek(fd, book_db.Book_ID * sizeof(book_db), SEEK_SET);
write(fd, (char *) &book_db, sizeof(book_db));
} // case1 END
else if(strncmp(cBuf, "4", 1) == 0){
break;
}
} // while
} // main
OUTPUT::
*@ubuntu:~/myshell/pl02$ gcc -o db_manage db_mng.c
*@ubuntu:~/myshell/pl02$ ./db_manage db_test.db
This is Database Book Management System
1. Add book
2. Update book
3. Find book
4. Exit
>> 1
Book_ID Title Publisher Author Price
1 unix shell sj 13000
This is Database Book Management System
1. Add book
2. Update book
3. Find book
4. Exit
>>
This is Database Book Management System
1. Add book
2. Update book
3. Find book
4. Exit
>>
The result I thought is that printf
statements are executed in the while statement, and when they meet fgets
and receive input while waiting for input, the conditional statement according to the input is executed.
However, the result value is input to fgets
, the result corresponding to the if statement "1" is executed, and the printf
statement is executed twice more.
How to solve this?
Desired result :: ex)
Book_ID Title Publishr author price
1 unix shell sj 13000
This is Seong-Jae Database Book Management System
1. Add book
2. Update book
3. Find book
4. Exit
>>
It makes the above wait state and executes the function when another value is entered later.
+) Currently, functions 2 and 3 have not been implemented, so only functions 1 and 4 are included.