-
-
Save 1995eaton/56f3256ce15b20500dc6 to your computer and use it in GitHub Desktop.
wc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <sys/stat.h> | |
int main(int argc, char *argv[]) { | |
if (argc == 1) { | |
return 0; | |
} | |
int tc = 0, | |
tl = 0, | |
tw = 0, | |
i; | |
for (i = 1; i < argc; i++) { | |
int characters = 0, | |
lines = 0, | |
words = 0; | |
char lastchar = '\n', | |
c; | |
struct stat buf; | |
stat(argv[i], &buf); | |
if (S_ISDIR(buf.st_mode) == 1) { | |
printf("wc: %s: Is a directory\n", argv[i]); | |
printf(" 0 0 0 %s\n", argv[i]); | |
continue; | |
} | |
FILE *doc = fopen(argv[i], "r"); | |
if (doc == 0) { | |
printf("wc: %s: No such file or directory\n", argv[i]); | |
continue; | |
} | |
while((c = fgetc(doc)) != EOF) { | |
switch (c) { | |
case '\n': | |
lines++; | |
break; | |
case ' ': | |
if (lastchar != ' ') { | |
words++; | |
} | |
break; | |
default: | |
if (lastchar == '\n') { | |
words++; | |
} | |
} | |
lastchar = c; | |
characters++; | |
} | |
printf(" %6d %4d %6d %s\n", lines, words, characters, argv[1]); | |
tc += characters; | |
tl += lines; | |
tw += words; | |
if (fclose(doc) != 0) { | |
printf("Error closing file\n"); | |
return 1; | |
} | |
} | |
if (argc > 2) { | |
printf(" %6d %4d %6d total\n", tl, tw, tc); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment