-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathsample.c
More file actions
79 lines (66 loc) · 1.29 KB
/
Copy pathsample.c
File metadata and controls
79 lines (66 loc) · 1.29 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
void usage(char **argv) {
fprintf(stderr, "Usage: %s [-n count] file ...\n", argv[0]);
exit(EXIT_FAILURE);
}
void sample(char *fname, int samples) {
int fd = open(fname, O_RDONLY);
if (fd < 0) {
perror(fname);
exit(EXIT_FAILURE);
}
struct stat st;
if (fstat(fd, &st) != 0) {
perror("stat");
exit(EXIT_FAILURE);
}
char *map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (map == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
int i;
for (i = 0; i < samples; i++) {
long long start = i * (long double) st.st_size / samples;
while (start > 0 && map[start - 1] != '\n') {
start--;
}
while (start < st.st_size) {
putchar(map[start]);
if (map[start] == '\n') {
break;
}
start++;
}
}
munmap(map, st.st_size);
close(fd);
}
int main(int argc, char **argv) {
int i;
extern char *optarg;
extern int optind;
int samples = 1000;
while ((i = getopt(argc, argv, "n:")) != -1) {
switch (i) {
case 'n':
samples = atoi(optarg);
break;
default:
usage(argv);
break;
}
}
if (optind >= argc) {
usage(argv);
}
for (i = optind; i < argc; i++) {
sample(argv[i], samples);
}
exit(EXIT_SUCCESS);
}