Home > front end >  How can I read a text from a file and insert the values in a Struct using C?
How can I read a text from a file and insert the values in a Struct using C?

Time:02-26

I'm trying to read a file and put the values in a Struct to sort then, but my code isn't working.

#include <stdio.h>
#include <stdlib.h>
 
struct person
{
    char Nome[50];
    int Idade;
    double Altura;
};


int main ()
{
    FILE *infile;
    struct person input;
     
    infile = fopen ("pessoas.txt", "r");
    if (infile == NULL)
    {
        fprintf(stderr, "\nError opening file\n");
        exit (1);
    }
     
    while(fread(&input, sizeof(struct person), 1, infile))
        printf ("Nome = %s Idade = %d Altura = %f\n", input.Nome,
        input.Idade, input.Altura);
 
    // close file
    fclose (infile);
 
    return 0;
}

My file is:

Maria

15

1.6

Joao

21

1.8

Abel

23

1.7

Joana

40

1.6

CodePudding user response:

You can use fscanf() to read file & populate the structure.

#include <stdio.h>
#include <stdlib.h>
 
struct person
{
    char Nome[50];
    int Idade;
    double Altura;
};


int main ()
{
    FILE *infile;
    struct person input;
     
    infile = fopen ("pessoas.txt", "r");
    if (infile == NULL)
    {
        fprintf(stderr, "\nError opening file\n");
        exit (1);
    }

    while(3 != fscanf(infile, "Is %d %lf", input.Nome, &input.Idade, &input.Altura))
        printf ("Nome = %s Idade = %d Altura = %lf\n", input.Nome, input.Idade, input.Altura);
 
    // close file
    fclose (infile);
 
    return 0;
}
  •  Tags:  
  • c
  • Related