-
Notifications
You must be signed in to change notification settings - Fork 0
/
datestamp.c
107 lines (87 loc) · 2.49 KB
/
datestamp.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
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "datestamp.h"
// datestamp
// typedef struct {
// int datestampId;
// int year;
// int month;
// int day;
// } datestamp_t;
void print_datestamp(datestamp_t *datestamp)
{
// datestamp cannot be NULL
if (datestamp == NULL) {
fprintf(stderr, "The datestamp is NULL\n");
exit(0);
}
printf("datestamp: %08d\n", datestamp->datestampId);
printf("\tMM/DD/YYYY: %02d/%02d/%04d\n", datestamp->month, datestamp->day,
datestamp->year);
}
datestamp_t *read_datestamp(int fileNum)
{
// set up file
FILE *fp;
char filename[1024];
sprintf(filename, "datestamps/datestamp_%08d.dat", fileNum);
// open file
fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Cannot open %s\n", filename);
exit(0);
}
// allocate memory for the record
datestamp_t *datestamp = (datestamp_t *)malloc(sizeof(datestamp_t));
// memory error
if (datestamp == NULL) {
fprintf(stderr, "Cannot allocate memory for city.\n");
exit(0);
}
// read datestamp
fread(&(datestamp->datestampId), sizeof(int), 1, fp);
fread(&(datestamp->year), sizeof(int), 1, fp);
fread(&(datestamp->month), sizeof(int), 1, fp);
fread(&(datestamp->day), sizeof(int), 1, fp);
fclose(fp);
return datestamp;
}
void write_datestamp(int fileNum, datestamp_t *datestamp)
{
// set up file
FILE *fp;
char filename[1024];
sprintf(filename, "datestamps/datestamp_%08d.dat", fileNum);
// open file
fp = fopen(filename, "wb");
if (!fp)
{
printf("Unable to open file.");
return;
}
// write user
fwrite(&(datestamp->datestampId), sizeof(int), 1, fp);
fwrite(&(datestamp->year), sizeof(int), 1, fp);
fwrite(&(datestamp->month), sizeof(int), 1, fp);
fwrite(&(datestamp->day), sizeof(int), 1, fp);
fclose(fp);
}
void free_datestamp(datestamp_t *datestamp)
{
if (datestamp == NULL) {
return;
}
free(datestamp);
}
int compare_datestamps(const void *a, const void *b)
{
return (int) (hash_datestamp((datestamp_t *)a) - hash_datestamp((datestamp_t *)b));
}
unsigned long hash_datestamp(datestamp_t *datestamp){
// YYYYMMDD
return ((unsigned long)(datestamp->year)*1000) +
((unsigned long)(datestamp->month) * 100) +
(unsigned long)(datestamp->day);
}