How to put each line of a txt file into a vector?

1

The file only contains 3 lines, which must be as follows:

Idade = 15
Nome = Alvaro
Apelido = Costa

This file is only open for reading with fopen in "r" mode.

So I have 3 variables declared in the code:

int idade;
char nome[10];
char apelido[10];

I need to fetch this information from the file and assign each variable its content -

I read on the internet that the fgets() function could read line by line and put line information to a vector but what I can do is just read the first line of the file with respect to age from now on it does not work.

With fscanf() I have to put everything into a vector first and there separating the information from that vector but I can not get all the contents of the file with this function.

What is the simplest way to do this?

My idea was to put each line to a separate vector and then searched with some function in the first digit vector and converted the string containing digits to integer and assigned to the variable ( int idade ).

Regarding the vector 2 that corresponded to the name I ignored the first positions that concerned "Name=" and took the string from that position forward forming a new vector with only the name. In relation to vector 3 I would do the same treatment as in vector 2, but the problem is that neither put the total information of the file into an array with it.

The ideal thing is that I would put each line of the file into a vector and from there I would already be able to use it.

I also share my code here:

int idade;
char nome[10];
char apelido[10];

void configuracoes(){

    // colocando aqui toda a informação do ficheiro

    char conteudo[100];

    // OU
    // será possivel pegar em cada linha de um ficheiro e colocar os seus caracteres directamente para cada um destes vetores?
    char linha1[10];
    char linha2[10];
    char linha3[10];


    FILE *f = fopen("dados.txt","r");

    // colocar o conteudo do ficheiro para dentro de um vetor

    // testativa de colocar todo o conteudo do ficheiro para dentro de um vetor // FALHADA
    int i;
    for(i=0; i != EOF; i++){
        conteudo[i] = fscanf(f,"%c", conteudo);
    }


    //fgets(conteudo,100,f);


    for(i=0; i<100; i++){
        printf("%c", conteudo[i]);
    }

    printf("\n");
    fclose(f);

    //printf("CONFIGURACAO APLICADA\n"); 
}

main(){
    configuracoes();

return 0;
}
    
asked by anonymous 23.10.2015 / 17:24

2 answers

1

Follow a solution using only fscanf() :

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

int main( int argc, char * argv[] )
{
    FILE * pf = NULL;

    int idade = 0;
    char nome[10] = {0};
    char apelido[10] = {0};

    pf = fopen( "ficheiro.txt", "r" );

    if(!pf)
        return 1;

    fscanf( pf, "Idade = %d\n", &idade );
    fscanf( pf, "Nome = %s\n", nome );
    fscanf( pf, "Apelido = %s\n", apelido );

    fclose(pf);

    printf( "Idade: %d\n", idade );
    printf( "Nome: %s\n", nome );
    printf( "Apelido: %s\n", apelido );

    return 0;
}

/* fim-de-arquivo */

I hope it's useful!

    
07.05.2016 / 01:49
0

There are several ways to solve the problem, the simplest would be:

#include <stdio.h>

int main()
{
    int idade;
    char nome[100];
    char apelido[100];
    char trash[100];

    FILE *f = fopen( "dados.txt", "r" );

    // Sempre importante verificar se nao houve erro na abertura
    if( f == NULL )  // Se houve erro na abertura
    {
        printf("Problemas na abertura do arquivo\n");
        return -1;
    }

    // Lendo a idade
    fscanf( f, "%s%s%d", trash, trash, &idade );
    printf( "Idade: %d \n", idade );
    // Lendo o nome
    fscanf( f, "%s%s%s", trash, trash, nome );
    printf( "Nome: %s \n", nome );
    // Lendo o apelido
    fscanf( f, "%s%s%s", trash, trash, apelido );
    printf( "Apelido: %s \n", apelido );

    close(f);
    return 0;
}

You can read the file information until you find a space using fscanf and store the variables you want. Another alternative that could be done is to use fgets and do a search until the '=' character. When you find the character you know that the next positions are given.

You can get the data using a memcpy, or strcpy and then convert the age to integer using atoi ();

Some considerations:

  • Beware of vector boundaries. If the name was greater than 10 would already give problem;
  • Always check error conditions;
  • fscanf returns the size of the read data, the data is stored in the address passed by parameter, careful;
27.10.2015 / 03:44