xv6-65oo2/user/wc.c

55 lines
834 B
C
Raw Normal View History

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