-
Notifications
You must be signed in to change notification settings - Fork 0
/
line-count.cpp
53 lines (38 loc) · 1.01 KB
/
line-count.cpp
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char *argv[]) {
int pagesize = 0;
for (size_t i = 1; i < (size_t) argc; ++i) {
char *str = argv[i];
struct stat buf;
int err = lstat(str, &buf);
if (err == -1) {
continue;
}
pagesize = buf.st_size;
int fd = open(str, O_RDONLY, 0);
void *mp = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
char *chr = (char *)mp;
int cnt = 0;
if (pagesize > 0) {
for (int offset = 0; offset < pagesize; ++offset) {
if (chr[offset] == '\n') {
cnt ++;
}
}
if (chr[pagesize - 1] != '\n') {
++cnt;
}
}
printf("%d\n", cnt);
}
}