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

Asked

Viewed 5,028 times

1

The file has only 3 lines as content, which must be so:

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];

and I need to retrieve that information from the file and assign to each of the variables its contents-

I read on the internet that function fgets() could read line by line and place line information for a vector but what I can do is just read the first line of the file that relates to age from there it no longer gives.

With the fscanf() I have to put everything into a vector first and then separate the information from that vector but I cannot with this function obtain all the contents of the file.

What’s the simplest way to do this?


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

In relation to vector 2 that would correspond to the name I ignored the first positions that referred to "Name = " and took advantage of the string of this forward position 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 putting the total file information inside an array with you.

The ideal I think would be to put each line of the file for an array and from there I already got away.


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;
}
  • If you are absolutely sure of the file format and are sure that the format will never change, you can do if (fscanf(f, "Idade =%d Nome =%.9s Apelido =%.9s", &idade, nome, apelido) != 3) /* erro */;

2 answers

1

Follows 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!

0

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

#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 go storing the variables you want. Another alternative that could be done is to use fgets and make a search until the character '='. When you find the character you know that the next positions are the die.

You can take 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 it would be a problem;
  • Always check error conditions;
  • fscanf returns the size of the data read, the data is stored at the address passed by parameter, care;

Browser other questions tagged

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