From 588ea34c6b65b6ab326d66186eaa5add2bfc2806 Mon Sep 17 00:00:00 2001 From: NRZ Code Date: Wed, 30 Apr 2025 16:55:53 -0300 Subject: [PATCH] =?UTF-8?q?Recebendo=20de=20stdin=20e=20v=C3=A1rios=20arqu?= =?UTF-8?q?ivos=20como=20argumentos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wc.c | 63 +++++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 45 insertions(+), 18 deletions(-) diff --git a/wc.c b/wc.c index 15b0c5a..e9c9da5 100644 --- a/wc.c +++ b/wc.c @@ -2,26 +2,53 @@ #include #include -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]; - int lines = 0, words = 0, bytes = 0; - FILE *stream = fopen(argv[1], "r"); - if (stream == NULL) { - perror("Erro ao abrir o arquivo"); - exit(EXIT_FAILURE); + int clines = 0, cwords = 0, cbytes = 0; + for (int i = 1; i < count; i++) { + int lines = 0, words = 0, bytes = 0; + FILE *stream = fopen(list[i], "r"); + 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) { - /* bytes */ - bytes += strlen(buffer); - char *str; - /* words */ - str = strdup(buffer); - while (strtok_r(str, " \t\n", &str) != NULL) - words++; - /* lines */ - lines++; + if (count > 2) + printf("%d %d %d total\n", clines, cwords, cbytes); +} + +int main(int argc, char **argv) { + char *list[2]; + if (argc < 2) { + list[1] = "/dev/stdin"; + wc(list, 2); + } else { + wc(argv, argc); } - printf("%d %d %d %s\n", lines, words, bytes, argv[1]); - fclose(stream); return EXIT_SUCCESS; }