How to create a C function that searches for words in txt files in a predefined directory?

Asked

Viewed 146 times

-2

void pesquisarexerword()
{

    DIR *dir;
    char *strdir, *strget,  t, *str;
    struct dirent *lsdir, *dirarq;
    FILE *arq;


    do{
        printf("\n Digite o Diretorio que Deseja Fazer a Pesquisa:\n");
        system("pause");
        fflush(stdin);//se desejar pesquisar outro diretotio ele volta aki
        gets(strdir);
        dir = opendir(strdir);//abrir o diretorio

        if( dir == NULL)
        {
        printf("\n\t****ERROR DIR NAO EXISTE*****"); return;
        }
        printf("\n Palavra que deseja Pesquisar:");
        gets(str);

        system("cls");

        do
        {
            dirarq = readdir(dir);//retorna o dir listando do arq
            arq = fopen(dirarq->d_name,"r");//abrir um arquivo no diretorio
            do
            {
                fgets(strget,244,arq);


                if(strcmp(str,strtok(strget,"")) == 0)//teste para achara a palavar no arquivo
                {
                printf("\n Nome do Arquivo Desejado:\n");
                printf("\n %s",dirarq->d_name);
               }

            }while(!feof(arq) || strcmp(str,strtok(strget,"")) != 0 );//teste se ha a frase dentro do arquivo ate acabar o arq

        }while( dir != NULL);//testa todo os arq do dir mencionado
        system("cls");

    printf("\n Deseja Pesquisar em outro Diretorio(Y/N)?:");
    scanf(" %c", &t);
    toupper(t);
    }while( t != 'N');

}
  • What’s the matter with you?

  • I need the user to type a directory to search in it one or two (in another code) words and so display the directory files that have these words..!

  • I have another code that it uses two words but stop tests and parameters for STRTOK() are bugged

  • I did not ask what the task was as a whole, but what specific problem is preventing you from completing this task. If I didn’t express myself well before, now I hope I’ve been straight to the point

  • is summarized in the third loop and the parameter for Strtok(), because you pass the string read from Arq to Strtok() as it is the same in the loop?

  • this problem could not solve...

Show 1 more comment

1 answer

0

You need to call Strtok the first time before entering the third loop.

token = strtok(strget, "");

Inside the third loop, you must call passing NULL as parameter:

token = strtok(NULL, "");

Browser other questions tagged

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