micro-utils/coreutils/wc.c
2023-10-21 15:05:49 +03:00

116 lines
1.9 KiB
C

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
/* cmd arguments l - lines c - bytes w - words */
unsigned int l_flag;
unsigned int c_flag;
unsigned int w_flag;
unsigned int words;
unsigned int bytes;
unsigned int lines;
/* Total */
unsigned int twords;
unsigned int tbytes;
unsigned int tlines;
void count(const int fd) {
char buf[4096];
ssize_t n = 0;
int in_word = 1;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
bytes += n;
for (ssize_t i = 0; i < n; i++) {
if (buf[i] == '\n')
lines++;
if (buf[i] == ' ' || buf[i] - '\t' < 5) {
if (!in_word) {
in_word = 1;
words++;
}
}
else
in_word = 0;
}
}
tbytes += bytes;
twords += words;
tlines += lines;
}
void print_count(const char *path, unsigned int plines, unsigned int pwords, unsigned int pbytes) {
if (l_flag)
printf("%u ", plines);
if (w_flag)
printf("%u ", pwords);
if (c_flag)
printf("%u", pbytes);
printf(" %s\n", path);
}
int main(const int argc, const char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-l"))
l_flag = 1;
else if (!strcmp(argv[i], "-c"))
c_flag = 1;
else if (!strcmp(argv[i], "-w"))
w_flag = 1;
else if (!strcmp(argv[i], "--help")) {
printf("wc [-l (lines)] [-c (bytes)] [-w (words)] [file1 file2...]\n");
return 0;
}
}
if (!w_flag && !l_flag && !c_flag) {
w_flag = 1;
l_flag = 1;
c_flag = 1;
}
if (i == argc) {
count(STDIN_FILENO);
print_count("", lines, words, bytes);
}
for (; i < argc; i++) {
int fd = open(argv[i], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "wc: %s\n", strerror(errno));
return 1;
}
count(fd);
if (i == argc - 1)
print_count("total", tlines, twords, tbytes);
else
print_count(argv[i], lines, words, bytes);
close(fd);
words = bytes = lines = 0;
}
return 0;
}