Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created July 4, 2014 12:04
Show Gist options
  • Save 1995eaton/56f3256ce15b20500dc6 to your computer and use it in GitHub Desktop.
Save 1995eaton/56f3256ce15b20500dc6 to your computer and use it in GitHub Desktop.
wc
#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