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?