1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "book.h"
/* Выводит в одну строку значения структуры */
void prnBook(const Book_t *pB, int num_row){
printf("%-3d%-20s%-30s%-7d%-5d\n", num_row, pB->author, pB->name, pB->year, pB->place);
}
/* Выводит заголовок */
void prnHead(void){
printf("%s\n# Author Name Year Place\n%s\n", SEP_LINE, SEP_LINE);
}
int main(void){
int count, answ, stop, i, same_year;
long int file_size;
FILE *dbf;
char buf[STR_LEN];
Book_t *books;
Book_t dummy;
if ( (dbf = fopen(DEFAULT_DB, "rb")) == NULL ){
printf("Can't open file %s\n", DEFAULT_DB);
exit(1);
}
fseek(dbf, 0, SEEK_END);
file_size = ftell(dbf);
rewind(dbf);
/* файл должен содержать некоторое количество объектов без остатка */
if ( file_size % sizeof(Book_t) ){
printf("ERROR: file %s corrupt!\n", DEFAULT_DB);
exit(1);
}
count = file_size / sizeof(Book_t);
if ( !count ){
printf("ERROR: file %s is empty!\n", DEFAULT_DB);
exit(1);
}
if ( (books = (Book_t *)calloc(count, sizeof(Book_t))) == NULL ){
printf("Not enough memory!\n");
exit(1);
}
if ( fread((void *)books, sizeof(Book_t), count, dbf) != count ){
printf("Unexpected end of file!\n");
exit(1);
}
fclose(dbf);
stop = 0;
while ( !stop ){
printf("\n%s\nBooks in db: %d\n", SEP_LINE, count);
printf("1 - show all, 2 - find place by author and name, 3 - show all of same author,\n");
printf("4 - count all of same year, 0 - exit\nChoice one: ");
answ = getchar();
getchar();
switch(answ){
case '1' :
prnHead();
for ( i = 0; i < count; i++ )
prnBook(books + i, i + 1);
printf("%s\n", SEP_LINE);
break;
case '2' :
printf("Author: ");
fgets(buf, STR_LEN, stdin);
buf[strlen(buf) - 1] = '\0';
strcpy(dummy.author, buf);
printf("Name: ");
fgets(buf, STR_LEN, stdin);
buf[strlen(buf) - 1] = '\0';
strcpy(dummy.name, buf);
for ( i = 0; i < count; i++ )
if ( !strcmp(books[i].author, dummy.author) && !strcmp(books[i].name, dummy.name) )
printf("\n*** Found in place %d\n", books[i].place);
break;
case '3' :
printf("Author: ");
fgets(buf, STR_LEN, stdin);
buf[strlen(buf) - 1] = '\0';
prnHead();
for ( i = 0; i < count; i++ )
if ( !strcmp(books[i].author, buf) )
prnBook(&books[i], i + 1);
break;
case '4' :
same_year = 0;
printf("Year: ");
fgets(buf, STR_LEN, stdin);
dummy.year = atoi(buf);
for ( i = 0; i < count; i++ )
if ( books[i].year == dummy.year )
same_year++;
printf("\n*** Fount %d books of %d year.\n", same_year, dummy.year);
break;
case '0' :
stop = 1;
break;
default :
printf("Bad choice - %c\n", answ);
break;
}
}
free(books);
return 0;
} |