Error in file code. c

Asked

Viewed 119 times

0

I need to make a simple search engine. Just open one arquivo.txt, search for a desired word by the user, check how many times a word appears in the file and if it exists in the file. But this giving an error that did not identify the origin, similar to the absence of &. Follows 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;
}
  • 1

    It would be interesting to inform the error message as well.

  • He says my executable program has stopped working.

  • It runs until asking for the desired word, when I put it, it says ".exe file has stopped working"

  • When you are debugandocannot capture the error?

  • No ... :/ No solution to the problem

1 answer

1

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

If you want to declare a string with 500 characters, change the statement to

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

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

fgets(buff,MAX,arq);

This will solve your application’s problem to stop working. There are other logic errors (in the call to strtok, for example), which you still need to fix before having the program working. But use a Debugger that you will get to see the easiest mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.