xv6-riscv-kernel/user/wc.c

55 lines
845 B
C
Raw Normal View History

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
2007-08-28 06:20:40 +02:00
char buf[512];
void
wc(int fd, char *name)
{
int i, n;
int l, w, c, inword;
l = w = c = 0;
inword = 0;
2024-06-15 16:55:06 +02:00
while((n = read(fd, buf, sizeof(buf))) > 0) {
for(i = 0; i < n; i++) {
2007-08-28 06:20:40 +02:00
c++;
if(buf[i] == '\n')
l++;
if(strchr(" \r\t\n\v", buf[i]))
inword = 0;
2024-06-15 16:55:06 +02:00
else if(!inword) {
2007-08-28 06:20:40 +02:00
w++;
inword = 1;
}
}
}
2024-06-15 16:55:06 +02:00
if(n < 0) {
2019-08-27 19:13:03 +02:00
printf("wc: read error\n");
2019-09-11 16:04:40 +02:00
exit(1);
2007-08-28 06:20:40 +02:00
}
2019-08-27 19:13:03 +02:00
printf("%d %d %d %s\n", l, w, c, name);
2007-08-28 06:20:40 +02:00
}
int
main(int argc, char *argv[])
{
int fd, i;
2024-06-15 16:55:06 +02:00
if(argc <= 1) {
2007-08-28 06:20:40 +02:00
wc(0, "");
exit(0);
2007-08-28 06:20:40 +02:00
}
2024-06-15 16:55:06 +02:00
for(i = 1; i < argc; i++) {
if((fd = open(argv[i], 0)) < 0) {
2019-08-27 19:13:03 +02:00
printf("wc: cannot open %s\n", argv[i]);
2019-09-11 16:04:40 +02:00
exit(1);
2007-08-28 06:20:40 +02:00
}
wc(fd, argv[i]);
close(fd);
}
exit(0);
2007-08-28 06:20:40 +02:00
}