-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise5-6.c
96 lines (84 loc) · 1.78 KB
/
exercise5-6.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
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
/* Exercise 5-6. This was easy.
*
* The created file goes from
*
* Hello,
*
* to
*
* Hello,world
*
* to
*
* HELLO,world
*
* to
*
* Giddayworld
*
* Real interesting stuff.
*
* */
int main(int argc, char *argv[]) {
int fd1 = open("/tmp/file.txt", O_RDWR | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR);
if (fd1 == -1) {
errExit("open /tmp/file.txt");
}
int fd2 = dup(fd1);
if (fd2 == -1) {
errExit("dup(fd1)");
close(fd1);
}
int fd3 = open("/tmp/file.txt", O_RDWR | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR);
if (fd2 == -1) {
close(fd1);
close(fd2);
errExit("open /tmp/file.txt");
}
int bytes_written = write(fd1, "Hello,", 6);
if (bytes_written == -1) {
close(fd1);
close(fd2);
close(fd3);
errExit("write");
}
bytes_written = write(fd2, "world", 6);
if (bytes_written == -1) {
close(fd1);
close(fd2);
close(fd3);
errExit("write");
}
if (lseek(fd2, 0, SEEK_SET) == -1) {
close(fd1);
close(fd2);
close(fd3);
errExit("lseek");
}
bytes_written = write(fd1, "HELLO,", 6);
if (bytes_written == -1) {
close(fd1);
close(fd2);
close(fd3);
errExit("write");
}
bytes_written = write(fd3, "Gidday", 6);
if (bytes_written == -1) {
close(fd1);
close(fd2);
close(fd3);
errExit("write");
}
return EXIT_SUCCESS;
}