FENIX_coreutils/wc.c

129 lines
2.3 KiB
C
Raw Normal View History

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
2020-12-13 20:28:17 +00:00
#include <unistd.h>
int count_words(FILE * file);
int count_newls(FILE * file);
int count_bytes(FILE * file);
int main(int argc, char ** argv) {
2020-12-13 20:28:17 +00:00
int flags = 0, do_multibyte = 0;
int c_byte = 0, c_nl = 0, c_word = 0;
int t_byte = 0, t_nl = 0, t_word = 0;
2020-12-13 20:28:17 +00:00
int i, error = 0; char c;
FILE * in_file;
2020-12-13 20:28:17 +00:00
while((c = getopt(argc, argv, "clwm")) != -1) {
switch(c) {
case 'c': flags |= 04; do_multibyte = 0; break;
case 'l': flags |= 01; break;
case 'w': flags |= 02; break;
case 'm': flags |= 04; do_multibyte = 1; break;
}
}
if((flags & 03) == 0) {
flags |= 04;
}
2020-12-13 20:28:17 +00:00
for(i = optind; i < argc; i++) {
in_file = fopen(argv[i], "r");
if(in_file == NULL) {
2020-12-13 20:28:17 +00:00
fprintf(stderr, "%s: couldn't open file %s\n", argv[0], argv[i]);
error = 1;
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);
}
2020-12-13 20:28:17 +00:00
if((argc - optind) > 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");
}
2020-12-13 20:28:17 +00:00
return error;
}
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;
}