Binary file storage

Asked

Viewed 4,013 times

2

In the program, I need to implement a structure that represents a student (name, age and enrollment). Using this structure, I have to write a program that reads the data of 5 students and stores it in a binary file.

I implemented the structure as follows:

typedef struct
{
    char nome[50];
    int idade;
    int matricula;
} aluno;

In the main function, I did as follows:

int main(int args, char *arg[])
{
    FILE *arq;
    arq = fopen("registro.txt", "wb");
    if(arq == NULL)
    {
        printf("Erro ao criar o arquivo");
        exit(1);
    }

    aluno registro[5];
    int i;

    for(i = 0; i < 5; i++)
    {
        gets(registro[i].nome);
        scanf("%d %d", &registro[i].idade, &registro[i].matricula);
        fprintf(arq, "%s | %d | %d\n", registro[i].nome, registro[i].idade, 
registro[i].matricula);
    }

    fclose(arq);
    return 0;
}

The program was compiled without any mistakes, but when I type the student information, I can only read the information of 3 students, and not 5 students as the exercise asks. I wonder why this is happening and would also like to know if this method of storing in a binary file is correct.

1 answer

2

You are opening the file in binary mode for recording (wb), but is not recording content correctly...

The recording and reading of the data shall be done with the functions fwrite() and fread() respectively.

Follows a code (tested) exemplifying the solution of the problem:

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


typedef struct aluno_s
{
    char nome[50];
    int idade;
    int matricula;
} aluno_t;


size_t gravar_registro( FILE * pf, char * nome, int idade, int mat )
{
    aluno_t a;

    strcpy( a.nome, nome );
    a.idade = idade;
    a.matricula = mat;

    return fwrite( &a, sizeof(aluno_t), 1, pf );
}


void ler_registro( FILE * pf, int mat )
{
    aluno_t a;

    while( fread( &a, sizeof(aluno_t), 1, pf ) )
    {
        if( a.matricula == mat )
        {
            printf( "Nome     : %s\n", a.nome );
            printf( "Idade    : %d\n", a.idade );
            printf( "Matricula: %d\n", a.matricula );
            printf( "\n" );

            break;
        }
    }
}


int main( int argc, char ** argv )
{
    FILE * arq = NULL;

    /* Abre arquivo para gravacao em modo binario... */
    arq = fopen( "registro.bin", "wb");

    if( !arq )
    {
        fprintf( stderr, "Erro ao abrir arquivo para gravacao.\n");
        return EXIT_FAILURE;
    }

    /* Cadastra 5 alunos... */
    gravar_registro( arq, "Albert Einstein", 65, 1234 );
    gravar_registro( arq, "Isaac Newton",    43, 3579 );
    gravar_registro( arq, "Galileu Galilei", 80, 2468 );
    gravar_registro( arq, "Michael Faraday", 77, 1000 );
    gravar_registro( arq, "James Maxwell",   43, 5050 );

    /* Fecha arquivo...*/
    fclose(arq);

    /* Abre arquivo para leitura em modo binario... */
    arq = fopen( "registro.bin", "rb");

    if( !arq )
    {
        fprintf( stderr, "Erro ao abrir arquivo para leitura.\n");
        return EXIT_FAILURE;
    }

    /* Faz a leitura dos alunos pelo codigo de matricula  */
    ler_registro( arq, 1234 );
    ler_registro( arq, 3579 );
    ler_registro( arq, 2468 );
    ler_registro( arq, 1000 );
    ler_registro( arq, 5050 );

    /* Fecha arquivo...*/
    fclose(arq);

    /* Sucesso */
    return EXIT_SUCCESS;
}

Exit:

$ ./cadastro
Nome     : Albert Einstein
Idade    : 65
Matricula: 1234

Nome     : Isaac Newton
Idade    : 43
Matricula: 3579

Nome     : Galileu Galilei
Idade    : 80
Matricula: 2468

Nome     : Michael Faraday
Idade    : 77
Matricula: 1000

Nome     : James Maxwell
Idade    : 43
Matricula: 5050
  • Thanks for the reply Lacobus! But I have a doubt. You used size_t. What is the purpose of it?

Browser other questions tagged

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