-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
83 lines (61 loc) · 1.41 KB
/
util.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
#include "util.h"
#include "phone_book.h"
char* getLine() {
int length = 10;
int count = 0;
char* buffer = (char*)malloc(sizeof(char) * length);
char* buf_ptr = &buffer[0];
char c;
*buf_ptr = '\0';
while((c = getchar()) != '\n') {
if(count >= (length - 1)) {
length += 10;
buffer = (char*)realloc(buffer, length);
}
++count;
*buf_ptr = c;
*(++buf_ptr) = '\0';
}
return buffer;
}
char* getLineFromFile(FILE *fp) {
fp = fopen("database.txt", "r");
int length = 10;
int count = 0;
char* buffer = (char*)malloc(sizeof(char) * length);
char* buf_ptr = &buffer[0];
char c;
*buf_ptr = '\0';
while((c = fgetc(fp)) != '\n') {
if(count >= (length - 1)) {
length += 10;
buffer = (char*)realloc(buffer, length);
}
++count;
*buf_ptr = c;
*(++buf_ptr) = '\0';
}
fclose(fp);
return buffer;
}
void Add(entry *arg, CLIENT *clnt) {
r_val *result;
char *name, *number;
puts("Enter the name : ");
name = getLine();
puts("Enter the number : ");
number = getLine();
arg->name = malloc(sizeof(char) * (strlen(name) + 1));
strcpy(arg->name, name);
arg->number = malloc(sizeof(char) * (strlen(number) + 1));
strcpy(arg->number, number);
arg->next = NULL;
result = add_to_database_1(arg, clnt);
if (result == NULL) {
clnt_perror(clnt, "call failed:");
}
else if(result->r_num == -1) {
printf("%s\n", result->r_error);
}
else printf("returned %i\n", result->r_num);
}