-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread.c
137 lines (111 loc) · 3.15 KB
/
read.c
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "read.h"
#include "memory_operations.h"
#include "struct.h"
#define READ_OK 1
#define END_ENTER "nothing"
#define N 256
#define ARTICLE "ARTICLE"
#define NAME "NAME"
#define COUNT "COUNT"
#define OK 0
#define INVALID_INPUT 1
#define INVALID_COUNT 2
#define NEGATIVE_COUNT 4
#define INVALID_SIZES 5
#define LOWER_ARTICLE 6
#define INVALID_KEY 7
static int check_upper(const char *str)
{
while (*str)
{
if (!isupper(*str))
{
return false;
}
++str;
}
return true;
}
int read_products(product_array_t *const products, FILE *f)
{
char article_checker[N];
char name_checker[N];
int i = 0;
while (true)
{
puts("Enter article: ");
if (fscanf(f, "%256s", article_checker) != READ_OK)
{
return INVALID_INPUT;
}
// проверка, что ввод закончен
if (!strcmp(article_checker, END_ENTER))
{
if (i == 0)
{
return INVALID_SIZES;
}
products->curr_size = i;
return OK;
}
// проверка, что артикл введен полностью заглавными
if (!check_upper(article_checker))
{
return LOWER_ARTICLE;
}
// если не хватает выделенной памяти, увеличивается вдвое
if (i >= products->curr_memory)
{
products->curr_memory *= 2;
if (change_memory((void**)&products, products->curr_memory, sizeof(product_t)))
{
return INVALID_MEMORY;
}
// зануление указателей, для которых еще не выделена память
null_pointers(products->array, products->curr_memory / 2, products->curr_memory);
}
// + 1 для терминального нуля
if (change_memory((void**)&products->array[i].article, strlen(article_checker) + 1, sizeof(char)))
{
return INVALID_MEMORY;
}
strcpy(products->array[i].article, article_checker);
puts("Enter name: ");
if (fscanf(f, "%256s", name_checker) != READ_OK)
{
return INVALID_INPUT;
}
if (change_memory((void**)&products->array[i].name, strlen(name_checker) + 1, sizeof(char)))
{
return INVALID_MEMORY;
}
strcpy(products->array[i].name, name_checker);
puts("Enter count: ");
if (fscanf(f, "%d", &products->array[i].count) != READ_OK)
{
return INVALID_INPUT;
}
if (products->array[i].count < 0)
{
fprintf(stderr, "Count should be >= 0\n");
return NEGATIVE_COUNT;
}
i++;
}
}
int read_sort_key(char *key, FILE *f)
{
puts("Enter sort key: ");
if (fscanf(f, "%8s", key) != READ_OK)
{
return INVALID_INPUT;
}
if (strcmp(key, ARTICLE) && strcmp(key, NAME) && strcmp(key, COUNT))
{
return INVALID_KEY;
}
return OK;
}