/
10-11-2.c
69 lines (58 loc) · 1.3 KB
/
10-11-2.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void touch(char *path);
static void experiment1(char *path);
static void experiment2(char *path);
static void experiment3(char *path, char *path2);
int main(int argc, char *argv[]) {
if (argc != 5) {
fprintf(stderr, "%s: invalid arguments\n", argv[0]);
exit(1);
}
experiment1(argv[1]);
experiment2(argv[2]);
experiment3(argv[3], argv[4]);
exit(0);
}
static void touch(char *path) {
FILE *fp = fopen(path, "w");
fclose(fp);
}
static void experiment1(char *path) {
touch(path);
int fd = open(path, O_RDONLY);
if (rename(path, "hoge") < 0) {
perror(path);
printf("ex1: failed to rename\n");
} else {
close(fd);
printf("ex1: succeed\n");
}
}
static void experiment2(char *path) {
touch(path);
int fd = open(path, O_RDONLY);
if (unlink(path) < 0) {
perror(path);
printf("ex2: failed to unlink\n");
} else {
close(fd);
printf("ex2: succeed\n");
}
}
static void experiment3(char *path, char *path2) {
touch(path);
touch(path2);
int fd = open(path, O_RDONLY);
if (rename(path2, "fuga") < 0) {
perror(path);
printf("ex3: failed to rename\n");
} else {
close(fd);
printf("ex3: succeed\n");
}
}