-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.c
112 lines (91 loc) · 2.35 KB
/
user.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
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "user.h"
// user
// typedef struct {
// int userId;
// int stateId;
// int cityId;
// char name[TEXT_SHORT];
// } user_t;
void print_user(user_t *user)
{
// user cannot be NULL
if (user == NULL) {
fprintf(stderr, "The user is NULL\n");
exit(0);
}
printf("User: %08d\n", user->userId);
printf("\t%-12s: %s\n", "name", user->name);
printf("\t%-12s: %08d\n", "cityId", user->cityId);
printf("\t%-12s: %08d\n", "stateId", user->stateId);
}
user_t *read_user(int fileNum)
{
// set up file
FILE *fp;
char filename[1024];
sprintf(filename, "users/user_%08d.dat", fileNum);
// open file
fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Cannot open %s\n", filename);
exit(0);
}
// allocate memory for the user
user_t *user = (user_t *)malloc(sizeof(user_t));
// memory error
if (user == NULL) {
fprintf(stderr, "Cannot allocate memory for user.\n");
exit(0);
}
fread(&(user->userId), sizeof(int), 1, fp);
fread(&(user->stateId), sizeof(int), 1, fp);
fread(&(user->cityId), sizeof(int), 1, fp);
fread(&(user->name[0]), sizeof(char), TEXT_SHORT, fp);
fclose(fp);
return user;
}
void write_user(int fileNum, user_t *user)
{
// set up file
FILE *fp;
char filename[1024];
sprintf(filename, "users/user_%08d.dat", fileNum);
// open file
fp = fopen(filename, "wb");
if (!fp)
{
printf("Unable to open file.");
return;
}
// write user
fwrite(&(user->userId), sizeof(int), 1, fp);
fwrite(&(user->stateId), sizeof(int), 1, fp);
fwrite(&(user->cityId), sizeof(int), 1, fp);
fwrite(&(user->name[0]), sizeof(char), TEXT_SHORT, fp);
fclose(fp);
}
void free_user(user_t *user)
{
if (user == NULL) {
return;
}
free(user);
}
int compare_users(const void *a, const void *b)
{
// compare by state id, then user id
int diff = (int) ((user_t*)a)->stateId - ((user_t*)b)->stateId;
if (diff == 0)
{
diff = (int) ((user_t*)a)->userId - ((user_t*)b)->userId;
}
return diff;
}
unsigned long hash_user(user_t *user)
{
return (unsigned long)user->userId;
}