Last active
October 6, 2022 09:58
-
-
Save Bruno02468/b3a6e9a4f7e826a1c51d7494c1a8d564 to your computer and use it in GitHub Desktop.
"Como ler um arquivo palavra a palavra em C?" - disse o pires
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* pires.c | |
* | |
* boa pires na moral, jogou o fino | |
* | |
* programa que lê arquivo .txt palavra a palavra | |
* | |
* ==> domínio público <== | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
/* nota: eu só uso o strchr da string.h por elegância, vc pode fazer uma | |
* comparação enorme para detectar delimitadores de palavra, tipo: | |
* if (tmp == ' ' || tmp == '\t' || tmp == '\n' || tmp == '\n' || ... ) { | |
* e se livrar da importação de string.h. | |
*/ | |
void fazer_coisa_com_palavra(char *palavra) { | |
printf("palavra: \"%s\"\n", palavra); | |
} | |
int main(int argc, char **argv) { | |
/* constantes */ | |
const int incremento = 5; | |
const char *delim = " \t\r\n"; | |
/* variáveis */ | |
int len_palavra, len_buffer; | |
char *palavra, tmp; | |
FILE *arq = NULL; | |
/* ler o arquivo com o nome fornecido */ | |
if (argc < 2) { | |
/* sem nome de arquivo, leremos do stdin */ | |
arq = stdin; | |
} else { | |
arq = fopen(argv[1], "r"); | |
if (!arq) { | |
perror("Impossível abrir o arquivo especificado"); | |
return EXIT_FAILURE; | |
} | |
} | |
/* inicializar o buffer de palavra */ | |
len_palavra = 0; | |
len_buffer = incremento; | |
palavra = malloc(len_buffer * sizeof(char)); | |
if (!palavra) { | |
printf("Impossível alocar %d bytes para buffer de palavra!\n", len_buffer); | |
return EXIT_FAILURE; | |
} | |
/* loop de leitura */ | |
while ((tmp = fgetc(arq)) != EOF) { | |
if (strchr(delim, tmp)) { | |
/* whitespace detectado -- imprimir palavra e resetar buffer */ | |
if (len_palavra) { | |
palavra[len_palavra] = '\0'; | |
fazer_coisa_com_palavra(palavra); | |
len_palavra = 0; | |
} | |
} else { | |
/* caractere normal detectado -- concatenar */ | |
if (len_palavra == (len_buffer - 1)) { | |
/* buffer cheio, vamos realocar */ | |
len_buffer += incremento; | |
palavra = realloc(palavra, len_buffer); | |
if (!palavra) { | |
printf("Impossível realocar %d bytes!\n", len_buffer); | |
return EXIT_FAILURE; | |
} | |
} | |
/* colocar o caractere lido no buffer de palavra */ | |
palavra[len_palavra++] = tmp; | |
} | |
} | |
/* EOF detectado... imprimir palavra no buffer, caso haja, e sair */ | |
if (len_palavra) { | |
palavra[len_palavra] = '\0'; | |
fazer_coisa_com_palavra(palavra); | |
len_palavra = 0; | |
} | |
free(palavra); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment