141 lines
2.6 KiB
C
Executable file
141 lines
2.6 KiB
C
Executable file
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
int count_words(FILE * file);
|
|
int count_newls(FILE * file);
|
|
int count_bytes(FILE * file);
|
|
|
|
int main(int argc, char ** argv) {
|
|
int flags = 0;
|
|
int c_byte = 0, c_nl = 0, c_word = 0;
|
|
int t_byte = 0, t_nl = 0, t_word = 0;
|
|
int i, fstart = 1;
|
|
FILE * in_file;
|
|
|
|
for(i = 1; i < argc; i++) {
|
|
if(argv[i][0] == '-') {
|
|
switch(argv[i][1]) {
|
|
case 'c': flags |= 04;fstart++; break;
|
|
case 'l': flags |= 01; fstart++; break;
|
|
case 'w': flags |= 02; fstart++; break;
|
|
default: break;
|
|
}
|
|
if(argv[i][2] != '\0') {
|
|
switch(argv[i][2]) {
|
|
case 'c': flags |= 04; break;
|
|
case 'l': flags |= 01; break;
|
|
case 'w': flags |= 02; break;
|
|
default: break;
|
|
}
|
|
if(argv[i][3] != '\0') {
|
|
switch(argv[i][3]) {
|
|
case 'c': flags |= 04; break;
|
|
case 'l': flags |= 01; break;
|
|
case 'w': flags |= 02; break;
|
|
default: break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else break;
|
|
}
|
|
|
|
if((flags & 03) == 0) {
|
|
flags |= 04;
|
|
}
|
|
|
|
for(i = fstart; i < argc; i++) {
|
|
in_file = fopen(argv[i], "r");
|
|
if(in_file == NULL) {
|
|
fprintf(stderr, "Cannot find file %s\n", argv[i]);
|
|
continue;
|
|
}
|
|
if(flags & 04) {
|
|
c_byte = count_bytes(in_file);
|
|
t_byte += c_byte;
|
|
}
|
|
if(flags & 01) {
|
|
c_nl = count_newls(in_file);
|
|
t_nl += c_nl;
|
|
}
|
|
if(flags & 02) {
|
|
c_word = count_words(in_file);
|
|
t_word += c_word;
|
|
}
|
|
|
|
if(flags & 01) {
|
|
printf("%d ", c_nl);
|
|
}
|
|
if(flags & 02) {
|
|
printf("%d ", c_word);
|
|
}
|
|
if(flags & 04) {
|
|
printf("%d ", c_byte);
|
|
}
|
|
|
|
printf("%s\n", argv[i]);
|
|
|
|
fclose(in_file);
|
|
}
|
|
|
|
if((argc - fstart) > 1) {
|
|
if(flags & 01) {
|
|
printf("%d ", t_nl);
|
|
}
|
|
if(flags & 02) {
|
|
printf("%d ", t_word);
|
|
}
|
|
if(flags & 04) {
|
|
printf("%d ", t_byte);
|
|
}
|
|
|
|
printf("total\n");
|
|
}
|
|
}
|
|
|
|
int count_words(FILE * file) {
|
|
int ret_val = 0, in_word = 0;
|
|
char c;
|
|
|
|
fseek(file, 0, SEEK_SET);
|
|
|
|
for(c = fgetc(file); c != EOF; c = fgetc(file)) {
|
|
if(c != ' ' && c != '\t' && c != '\n') {
|
|
in_word = 1;
|
|
}
|
|
else if(in_word) {
|
|
ret_val++;
|
|
in_word = 0;
|
|
}
|
|
}
|
|
|
|
if(in_word) ret_val++;
|
|
|
|
return ret_val;
|
|
}
|
|
|
|
int count_newls(FILE * file) {
|
|
char c; int ret_val = 0;
|
|
|
|
fseek(file, 0, SEEK_SET);
|
|
|
|
for(c = fgetc(file); c != EOF; c = fgetc(file)) {
|
|
if(c == '\n') {
|
|
ret_val++;
|
|
}
|
|
}
|
|
|
|
return ret_val;
|
|
}
|
|
|
|
int count_bytes(FILE * file) {
|
|
char c; int ret_val = 0;
|
|
|
|
fseek(file, 0, SEEK_SET);
|
|
|
|
for(c = fgetc(file); c != EOF; c = fgetc(file)) {
|
|
ret_val++;
|
|
}
|
|
|
|
return ret_val;
|
|
}
|