-
Notifications
You must be signed in to change notification settings - Fork 39
/
wc-l-syscall.c
60 lines (53 loc) · 1.15 KB
/
wc-l-syscall.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
/*
wc-l-syscall.c -- Simple "wc -l" command (system call version)
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void do_word_count(int fd, const char *path);
static void die(const char *s);
int
main(int argc, char *argv[])
{
int i;
if (argc < 2) {
fprintf(stderr, "%s: file name not given\n", argv[0]);
exit(1);
}
for (i = 1; i < argc; i++) {
char *path = argv[i];
int fd = open(path, O_RDONLY);
if (fd < 0) die(path);
do_word_count(fd, path);
if (close(fd) < 0) die(path);
}
exit(0);
}
#define BUFFER_SIZE 2048
static void
do_word_count(int fd, const char *path)
{
unsigned long count = 0;
for (;;) {
unsigned char buf[BUFFER_SIZE];
int n = read(fd, buf, sizeof buf);
if (n < 0) die(path);
if (n == 0) break;
unsigned long i;
for (i = 0; i < BUFFER_SIZE; i++) {
if (buf[i] == '\n') {
count++;
}
}
}
printf("%lu\n", count);
}
static void
die(const char *s)
{
perror(s);
exit(1);
}