Error in file code. W

0

I need to do a simple search engine. Just open arquivo.txt , search for a word desired by the user, check how many times a word appears in the file and whether it exists in the file. But this is giving an error that I did not identify the origin, similar to the absence of & . Here is my code:

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#define max 500
int main(){
char pprocurada[100];
char *buff[500];
int contpp=0;
FILE *arq;
arq=fopen("C:\Users\jvict_000\Desktop\JoaoVictorF\FaroesteCaboclo.txt", "r");
if(arq==NULL)
    printf("n%co foi possivel abrir o arquivo\n",132);
printf("Digite a palavra a ser pesquisada\n");
fflush(stdin);
gets(pprocurada);
fflush(stdin);
fgets(*buff,max,arq);
while (!feof(arq)) {
    if(contpp==0) {
        strtok(*buff," ");
        if(strcmp(pprocurada,*buff)==0)
            contpp++;
    } else {
        strtok(NULL," ");
        if(strcmp(pprocurada,*buff)==0)
            contpp++;
    }
    fflush(stdin);
    fgets(*buff,max,arq);
}
fclose(arq);
if(contpp!=0)
    printf("Pesquisa terminada, a palavra %s foi encontrada: %d vezes",pprocurada,contpp);
else {
    printf("A palavra %s n%co foi encontrada no arquivo",pprocurada,132);
}
return 0;
}
    
asked by anonymous 18.02.2016 / 02:07

1 answer

1

The problem is that the buff variable is defined as an array of 500 string elements , where string == pointer to char ( char * ) - but those pointers are pointing to addresses arbitrary memory.

If you want to declare a string of 500 characters, change the declaration to

char buff[MAX]; // é convenção declarar constantes/macros em MAIUSCULAS

Since this declares a string ( char * ) with size 500 allocated on the stack. And when you use this variable (in calls to fgets , strcmp and strtok ), you do not need to rename the pointer, you can use it directly:

fgets(buff,MAX,arq);

This will solve your application problem stop working. There are other logic errors (in the strtok call, for example), which you still need to fix before you have the program working. But use a debugger that will get you to see the error easier.

    
18.02.2016 / 05:15