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
|
// Authour: jasa7131
// CSCI3753 SP2024
// PA2 File Tester
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_SIZE 256
int main(int argc, char **argv) {
if (argc < 2) {
printf("%s error: missing filename\n", argv[0]);
exit(EXIT_FAILURE);
}
int fd = open(argv[1], O_RDWR);
if (!fd) {
printf("%s error: invalid filename\n", argv[0]);
exit(EXIT_FAILURE);
}
char *read_data, write_data[MAX_SIZE], input;
int bytes, offset, whence;
printf("Option (r for read, w for write, s for seek): ");
while (scanf("%c", &input) != EOF) {
switch (input) {
case 'r':
printf("Enter the number of bytes you want to read: ");
scanf("%d", &bytes);
read_data = (char *)malloc(bytes * sizeof(char));
if (read(fd, read_data, bytes) < 0) {
fprintf(stderr, "%s error: read failed\n", argv[0]);
free(read_data);
exit(EXIT_FAILURE);
}
printf("%s\n", read_data);
free(read_data);
break;
case 'w':
printf("Enter the data you want to write: ");
scanf(" %255[^\n]", write_data);
int n = strlen(write_data) + 1;
write_data[n] = '\0';
if (write(fd, write_data, n) < 0) {
fprintf(stderr, "%s error: write failed\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 's':
printf("Enter an offset value: ");
scanf("%d", &offset);
printf("Enter a value for whence: ");
scanf("%d", &whence);
if (lseek(fd, offset, whence) < 0) {
fprintf(stderr, "%s error: seek failed\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
default:
printf("Option (r for read, w for write, s for seek): ");
}
}
close(fd);
return EXIT_SUCCESS;
}
|