-
Notifications
You must be signed in to change notification settings - Fork 64
/
odirect_write.c
75 lines (60 loc) · 1.63 KB
/
odirect_write.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
#ifdef __linux__
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#ifndef O_DIRECT
#define O_DIRECT 00040000 /* direct disk access hint */
#endif
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "Expected 1 argument: the file to read.\n");
return 1;
}
int fd = open(argv[1], O_WRONLY | O_CREAT | O_DIRECT, 0644);
if (fd == -1) {
perror("failed to open file");
return 1;
}
const size_t buf_size = 4096;
unsigned char* buf = mmap(NULL, buf_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
if (buf == MAP_FAILED) {
perror("mmap failed");
return 1;
}
while (1) {
if (feof(stdin)) {
break;
}
memset(buf, 0, buf_size);
size_t amt_read = fread(buf, 1, buf_size, stdin);
if (ferror(stdin)) {
perror("failed to read stdin");
return 1;
}
if (amt_read == 0) {
continue;
}
ssize_t res = write(fd, buf, buf_size);
if (res == -1) {
perror("failed to write");
return 1;
}
if ((size_t)res != buf_size) {
// Too lazy to write a loop here unless it turns out to be necessary.
fprintf(stderr, "Failed to write exactly %lu bytes", (unsigned long)amt_read);
}
}
munmap(buf, buf_size);
return 0;
}
#else // __linux__
#include <stdio.h>
int main(void) {
fprintf(stderr, "Not supported on this platform.\n");
return 1;
}
#endif // __linux__