How to read text files and put the words in a vector?

2

I need to make a code that reads a text file (txt) and save only the words in the positions of a vetor , below my code follows:

int main(int argc, char** argv) 
{
    FILE *file;
    file = fopen("arquivo.txt", "r");

    char x[100];

    while((x[i] = fgetc(file)) != ' ' && x[i] != '\t')
    {
        i++;
    }

    j = 1;

    x[i+1] = '
int main(int argc, char** argv) 
{
    FILE *file;
    file = fopen("arquivo.txt", "r");

    char x[100];

    while((x[i] = fgetc(file)) != ' ' && x[i] != '\t')
    {
        i++;
    }

    j = 1;

    x[i+1] = '%pre%';
    printf("%s", x);

    fclose(file);

    return (EXIT_SUCCESS);
}
'; printf("%s", x); fclose(file); return (EXIT_SUCCESS); }

But from this I do not know how to do it.

    
asked by anonymous 16.01.2016 / 16:27

1 answer

3

You have to keep in mind that a string vector in C is actually an array of char , see the example below:

char* palavras[50];

Above I declared a vector with a pointer pointing to the word. This vector has the capacity to store 50 words, and the number of characters of the words can be any, because it will depend on the size of the word that will be in the palavras.txt file.

I assumed that the content structure of the palavras.txt text file looks like this:

computador
gato
mundo
cachorro
casa
stack
over
flow

Here is an example of a program that reads the words from the text file and stores the words read:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int i = 0;
    int numPalavras = 0;
    char* palavras[50];
    char line[50];

    FILE *arquivo;
    arquivo = fopen("palavras.txt", "r");

    if (arquivo == NULL)
        return EXIT_FAILURE;

    while(fgets(line, sizeof line, arquivo) != NULL)
    {
        //Adiciona cada palavra no vetor
        palavras[i] = strdup(line);

        i++;

        //Conta a quantidade de palavras
        numPalavras++;
    }

    int j;

    for (j = 0; j < numPalavras; j++)
        printf("\n%s", palavras[j]); //Exibi as palavras que estao no vetor.

    printf("\n\n");

    fclose(arquivo);

    return EXIT_SUCCESS;
}

Program exit:

computador

gato

mundo

cachorro

casa

stack

over

flow

Notice that I had to use the palavras function to return the string pointer that is stored in strdup which in this case is the word, without it all the word pointers would point to the same location, otherwise I would mistake to point to the last word of the file line , to prove it is enough to make the test replacing the line flow with palavras[i] = strdup(line); to see the result.

To learn more about the palavras[i] = line; function, see this question .

Sources:
Reading lines from c file and putting the strings into an array . How do I create an array of strings in C?

    
16.01.2016 / 22:42