-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathwrite_read.c
53 lines (48 loc) · 1.2 KB
/
write_read.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
/* Write to a file, then read it back to memory. */
#include "common.h"
int main(void) {
char buf[] = { 'a', 'b', 'c', 'd' };
char buf2[] = { 'e', 'f', 'g', 'h' };
int f, ret;
size_t off;
/* write
*
* It could return less than the requested size if e.g. no more disk space.
* and that is not considered an error.
*/
f = open(__FILE__ ".tmp", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
if (f == -1) {
perror("open");
assert(0);
}
ret = write(f, buf, sizeof(buf));
if (ret == -1) {
perror("write");
assert(0);
}
if ((size_t)ret < sizeof(buf)) {
assert(0);
}
close(f);
/* read
*
* Could return less than requested, specially when reading from pipes.
* So we need to keep reading. 0 means EOF.
*/
off = 0;
f = open(__FILE__ ".tmp", O_RDONLY);
if (f == -1) {
perror("open");
assert(0);
}
while ((ret = read(f, buf2 + off, sizeof(buf) - off))) {
off += ret;
if (ret == -1) {
perror("read");
assert(0);
}
}
close(f);
assert(!memcmp(buf, buf2, sizeof(buf)));
return EXIT_SUCCESS;
}