-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecordfile.c
More file actions
135 lines (110 loc) · 2.59 KB
/
Copy pathrecordfile.c
File metadata and controls
135 lines (110 loc) · 2.59 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define RECORD_SIZE 32 // bytes
static void seek_to_record(int fd, int record_num)
{
off_t offset = (off_t)record_num * RECORD_SIZE;
if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
perror("lseek");
exit(1);
}
}
/**
* Read the record from the buffer
*/
void read_record(int fd, int record_num, char *buffer)
{
seek_to_record(fd, record_num);
memset(buffer, 0, RECORD_SIZE);
ssize_t bytes_read = read(fd, buffer, RECORD_SIZE);
if (bytes_read == -1) {
perror("read");
exit(1);
}
}
/**
* Write the record to the buffer
*/
void write_record(int fd, int record_num, char *buffer)
{
seek_to_record(fd, record_num);
ssize_t bytes_written = write(fd, buffer, RECORD_SIZE);
if (bytes_written == -1) {
perror("write");
exit(1);
}
}
///////////////////////////////////////////////////////////
// Understand but don't modify the code below this point //
///////////////////////////////////////////////////////////
/**
* Different app modes
*/
enum mode {
MODE_READ,
MODE_WRITE
};
/**
* App context
*/
struct context {
enum mode mode;
int rec_num;
char *buf;
};
/**
* Print a usage message and exit
*/
void usage(void)
{
fprintf(stderr, "usage: recordfile read rec_num | write rec_num data\n");
exit(1);
}
/**
* Parse command line.
*/
void parse_command_line(int argc, char *argv[], struct context *context)
{
if (argc < 2) usage();
if (argv[1][0] == 'r') {
if (argc != 3) usage();
context->mode = MODE_READ;
context->rec_num = atoi(argv[2]);
} else if (argv[1][0] == 'w') {
if (argc != 4) usage();
context->mode = MODE_WRITE;
context->rec_num = atoi(argv[2]);
strncpy(context->buf, argv[3], RECORD_SIZE);
context->buf[RECORD_SIZE-1] = '\0';
} else
usage();
}
/**
* Main
*/
int main(int argc, char *argv[])
{
char buf[RECORD_SIZE] = {0};
struct context context = { .buf = buf };
parse_command_line(argc, argv, &context);
// Open the file
int fd;
if ((fd = open("recordfile.dat", O_RDWR|O_CREAT, 0600)) == -1) {
perror("open");
return 2;
}
// Read or write records
switch (context.mode) {
case MODE_READ:
read_record(fd, context.rec_num, buf);
printf("%d: %s\n", context.rec_num, buf);
break;
case MODE_WRITE:
write_record(fd, context.rec_num, context.buf);
break;
}
close(fd);
}