-
Notifications
You must be signed in to change notification settings - Fork 0
/
timestamp.c
102 lines (82 loc) · 2.29 KB
/
timestamp.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
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "timestamp.h"
// timestamp
// typedef struct {
// int timestampId;
// int hour;
// int minute;
// } timestamp_t;
void print_timestamp(timestamp_t *timestamp)
{
// timestamp cannot be NULL
if (timestamp == NULL) {
fprintf(stderr, "The timestamp is NULL\n");
exit(0);
}
printf("Timestamp: %08d\n", timestamp->timestampId);
printf("\tHH:MM: %02d:%02d\n", timestamp->hour, timestamp->minute);
}
timestamp_t *read_timestamp(int fileNum)
{
// set up file
FILE *fp;
char filename[1024];
sprintf(filename, "timestamps/timestamp_%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
timestamp_t *timestamp = (timestamp_t *)malloc(sizeof(timestamp_t));
// memory error
if (timestamp == NULL) {
fprintf(stderr, "Cannot allocate memory for timestamp.\n");
exit(0);
}
// read timestamp
fread(&(timestamp->timestampId), sizeof(int), 1, fp);
fread(&(timestamp->hour), sizeof(int), 1, fp);
fread(&(timestamp->minute), sizeof(int), 1, fp);
fclose(fp);
return timestamp;
}
void write_timestamp(int fileNum, timestamp_t *timestamp)
{
// set up file
FILE *fp;
char filename[1024];
sprintf(filename, "timestamps/timestamp_%08d.dat", fileNum);
// open file
fp = fopen(filename, "wb");
if (!fp)
{
printf("Unable to open file.");
return;
}
// write user
fwrite(&(timestamp->timestampId), sizeof(int), 1, fp);
fwrite(&(timestamp->hour), sizeof(int), 1, fp);
fwrite(&(timestamp->minute), sizeof(int), 1, fp);
fclose(fp);
}
void free_timestamp(timestamp_t *timestamp)
{
if (timestamp == NULL) {
return;
}
free(timestamp);
}
int compare_timestamps(const void *a, const void *b)
{
return (int) (hash_timestamp((timestamp_t *)a) - hash_timestamp((timestamp_t *)b));
}
unsigned long hash_timestamp(timestamp_t *timestamp){
// HHMM
return (((unsigned long)timestamp->hour) * 100) +
((unsigned long)timestamp->minute);
}