Recebendo de stdin e vários arquivos como argumentos

This commit is contained in:
NRZ Code 2025-04-30 16:55:53 -03:00
parent d4e47bf489
commit 588ea34c6b

63
wc.c
View file

@ -2,26 +2,53 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
int main(int argc, char **argv) { int intlen(int number) {
// return ceil(log10(number+1));
char buffer[10];
sprintf(buffer, "%d", number);
return strlen(buffer);
}
void wc(char **list, int count) {
char buffer[BUFSIZ]; char buffer[BUFSIZ];
int lines = 0, words = 0, bytes = 0; int clines = 0, cwords = 0, cbytes = 0;
FILE *stream = fopen(argv[1], "r"); for (int i = 1; i < count; i++) {
if (stream == NULL) { int lines = 0, words = 0, bytes = 0;
perror("Erro ao abrir o arquivo"); FILE *stream = fopen(list[i], "r");
exit(EXIT_FAILURE); if (stream == NULL) {
perror("Erro ao abrir o arquivo");
exit(EXIT_FAILURE);
}
while (fgets(buffer, BUFSIZ, stream) != NULL) {
/* bytes */
bytes += strlen(buffer);
char *str;
/* words */
str = strdup(buffer);
while (strtok_r(str, " \t\n", &str) != NULL)
words++;
/* lines */
lines++;
}
if (strcmp(list[i], "/dev/stdin") == 0)
list[i] = "";
clines += lines;
cwords += words;
cbytes += bytes;
printf("%d %d %d %s\n", lines, words, bytes, list[i]);
fclose(stream);
} }
while (fgets(buffer, BUFSIZ, stream) != NULL) { if (count > 2)
/* bytes */ printf("%d %d %d total\n", clines, cwords, cbytes);
bytes += strlen(buffer); }
char *str;
/* words */ int main(int argc, char **argv) {
str = strdup(buffer); char *list[2];
while (strtok_r(str, " \t\n", &str) != NULL) if (argc < 2) {
words++; list[1] = "/dev/stdin";
/* lines */ wc(list, 2);
lines++; } else {
wc(argv, argc);
} }
printf("%d %d %d %s\n", lines, words, bytes, argv[1]);
fclose(stream);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }