-
-
Save kamikat/9680517 to your computer and use it in GitHub Desktop.
咱这是多久没写 C 了……
This file contains hidden or 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 <stdlib.h> | |
#include <string.h> | |
#define BUFFER_SIZE (1024) | |
int main (int argc, char **argv) { | |
int flags = 0; | |
char* path = NULL; | |
argv++; argc--; // Skip $0 | |
while (argc) { | |
fprintf(stderr, "DEBUG argv %s\n", *argv); | |
if (!strcmp(*argv, "-c")) { | |
flags |= 0x04; | |
} else if (!strcmp(*argv, "-w")) { | |
flags |= 0x02; | |
} else if (!strcmp(*argv, "-l")) { | |
flags |= 0x01; | |
} else { | |
path = *argv; | |
} | |
argv++; argc--; | |
} | |
if (flags == 0) flags = 0x07; | |
FILE *fp = freopen(path, "r", stdin); | |
char buffer[BUFFER_SIZE]; | |
size_t buflen = 0; | |
int line_count = 0; | |
int word_count = 0; | |
int char_count = 0; | |
char last_char = ' '; | |
do { | |
buflen = fread(buffer, sizeof(char), BUFFER_SIZE, fp); | |
for (int i = 0; i != buflen; i++) { | |
char it = buffer[i]; | |
if (it == '\n') { line_count++; it = ' '; } | |
if (it != last_char && it == ' ') word_count++; | |
last_char = it; | |
} | |
char_count += buflen; | |
} while (buflen == BUFFER_SIZE); | |
if (last_char != ' ') word_count++; | |
if (flags & 0x01) fprintf(stdout, "%d\t", line_count); | |
if (flags & 0x02) fprintf(stdout, "%d\t", word_count); | |
if (flags & 0x04) fprintf(stdout, "%d\t", char_count); | |
fprintf(stdout, "%s\n", path); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
用时1h……