sábado, 11 de junho de 2011

CONTANDO O NÚMERO DE VEZES QUE UMA PALAVRA APARECE EM UM ARQUIVO

Como saber quantas vezes uma certa palavra apareceu no arquivo???
Bem pode-se pensar de dois jeitos.
Primeiro: Cada palavra esta em um linha do arquivo! (jeito bem simples de fazer, pensar!)
Segundo: Tudo bagunçado(jeito mais hard de fazer, exige maior lógica)


RESOLVENDO....

PRIMEIRO :


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

int main()
{
FILE *arq;
char name[15], test[15], aux[15];
int i, cont=0;
printf("\nDIGITE O NOME DO ARQUIVO\n");
gets_s(name);
arq=fopen(name,"r");
if(!arq)
{
printf("ERRO AO ABRIR O ARQUIVO");
getch();
exit (1);
}
printf("\nDIGITE A PALAVRA QUE DESEJAR\n");
gets_s(test);
while(!feof(arq))
{
fscanf(arq,"%s", &aux);
if(strcmp(test,aux)==0)
cont++;
}
printf("\nA PALAVRA %s SE REPETIU %d vezes",test, cont);
getch();
return 1;
}

OUTRO JEITO: CONTANDO LETRA POR LETRA


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>



int ler(char *nome);
int main()

{
int npalavras=0;
char nome[15];
printf("\n\nDigite o nome do arquivo\n");
fflush(stdin);
gets(nome);
npalavras=ler(nome);//CHAMA A FUNCÇAO LER
printf("\nExite %d palavras", npalavras);
getch();
return 1;

}
int ler(char *nome)//funcao que le todo arquivo e recebe com parametro um string com o nome do arquivo
{
FILE *p;//ponteiro pra arquivo
char test[15], c;
int i=0, j=0, cont=0,xis=0,tam;
p=fopen(nome, "r");//abrindo arquivo
if(!p)
{
printf("\nERRO: ARQUIVO NAO EXISTE OU PODE ESTAR CORROMPIDO!! ");
getch();
exit (1);
}
printf("\n\nDigite a palavra\n\n");
fflush(stdin);
gets(test);
tam=strlen(test);//contando o tamanho da palavra
while((c=getc(p))!=EOF)//le ate o fim do arquivo
{
if(c=='\n')//caso tenha uma quebra de linha, nao é contado
xis=0;

else{
if(c==test[i])
{
i++;//enquanto a letras da palavra desejada e do arquivo forem batendo... vai incrementando o i
xis=1;
}

else
{
i=0;//caso mude, i==0
xis=0;}
if(xis==1 && i==tam){//se, sempre for iguais as letras e chegar no tamanha da palavra... conta uma!
cont++;
i=0;}}


}
fclose(p);//fecha o arquivo
return cont;//retorna o numero de palavras
}
//COMENTEM!!!

2 comentários: