Store vector file contents in C

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 number of words.

The code performs strange storage. When I try to print, a random character rain 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]);
    }

}
    
asked by anonymous 06.12.2015 / 07:13

2 answers

1

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 that therefore the internal file pointer is at the end.

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

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

Do not go back to the beginning, your while does nothing by leaving the vetor_palavras array uninitialized, with garbage.

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

    
07.12.2015 / 10:32
0

The error was occurring when I asked fscanf to write to the vector (char **). I corrected the error using the fseek () function as proposed by the colleague and asking fscanf to write to a string (char *) and then using the function strcpy () of the string.h library to copy the contents of the string to the vector position. Problem solved.

    
08.12.2015 / 18:27