Recebendo de stdin e vários arquivos como argumentos
This commit is contained in:
parent
d4e47bf489
commit
588ea34c6b
1 changed files with 45 additions and 18 deletions
63
wc.c
63
wc.c
|
@ -2,26 +2,53 @@
|
|||
#include <stdlib.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];
|
||||
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;
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue