Vector file content in C

Asked

Viewed 3,931 times

2

I need to read a text file and store each word of the file in a vector position. The reading was done normally and the file was passed by parameter such as the amount of words.

The code performs the storage in a strange way. When I try to print, a rain of random characters appears.

Code:

void armazena_vetor(FILE* dicionario, int numero_palavras) //armazena o dicionario em um vetor
{

    char vetor_palavras[numero_palavras][15];
    int posicao;
    int i;

    posicao = 0;
    printf("%d", numero_palavras);

    while(((fscanf(dicionario, "%s", vetor_palavras[posicao])) != EOF) && (posicao < numero_palavras)) //Escreve uma palavra em cada posicao do vetor
    {
        posicao++; //Incremento de posicao
    }

    for (i=0;i<numero_palavras;i++) //teste imprime
    {
        printf("%s \n", vetor_palavras[i]);
    }

}
  • How this file structure your containing words?

  • It is a dictionary.txt: Pineapple Avocado.... . . . Where words are separated by " n"

  • Yes, like this organized the words in the archive, in list?

  • Post your code calling your function armazena_palavra.

1 answer

2


How do you know how many words the file has?

My intuition tells me that you have already read the file once, before calling this function, and therefore the internal sharpener of the file is at the end.

You need to get the internal file pointer back to the beginning! Use fseek()

fseek(dicionario, 0, SEEK_SET); // apontar para o principio

Without going back to the beginning, yours while does nothing leaving the array vetor_palavras uninitialized, with garbage.

Another thing: The use of "while(!feof())" or similar is wrong!

  • The error was occurring when I asked fscanf to write on the vector(char**). Fixed the error using the fseek() function as proposed by the colleague and asked fscanf to write in a string (char*) and then using the strcpy() function of the string library. h to copy the contents of the string to the vector at the desired position. Solved problem.

Browser other questions tagged

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