Recover struct data in C

Asked

Viewed 720 times

0

How do I save a Struct to a C file and recover that data in another run of the program?

2 answers

0


Here is an illustrative (tested) example of how to read and write data from a "struct" into a binary file.

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

#define ARQUIVO  "teste.dat"

typedef struct registro_s
{
    int a;
    int b;
    int c;
} registro_t;


size_t gravar_registro( const char * arq, registro_t * rec )
{
    size_t nbytes = 0L;
    FILE * fp = fopen( arq, "wb" );

    if(!fp)
        return 0;

    nbytes = fwrite( rec, sizeof(registro_t), 1, fp );

    fclose(fp);

    return nbytes;
}


size_t ler_registro( const char * arq, registro_t * rec )
{
    size_t nbytes = 0L;
    FILE * fp = fopen( arq, "rb" );

    if(!fp)
        return 0;

    nbytes = fread( rec, sizeof(registro_t), 1, fp );

    fclose(fp);

    return nbytes;
}


void exibir_registro( registro_t * rec )
{
    printf("a = %d\n", rec->a );
    printf("b = %d\n", rec->b );
    printf("c = %d\n", rec->c );
}


int main( int argc, char * argv[] )
{
    registro_t rec;

    if( argc <= 1)
        return 1;

    if( !strcmp(argv[1], "--ler") )
    {
        if( !ler_registro( ARQUIVO, &rec ) )
        {
            printf( "Erro lendo Arquivo: %s\n", ARQUIVO );
            return 1;
        }

        exibir_registro( &rec );
    }
    else if( !strcmp(argv[1], "--gravar") )
    {
        rec.a = atoi(argv[2]);
        rec.b = atoi(argv[3]);
        rec.c = atoi(argv[4]);

        gravar_registro( ARQUIVO, &rec );
    }

    return 0;
}

Compiling:

$ gcc -Wall struct.c -o struct

Testing recording:

$ ./struct --gravar 246 999 735

Reading test:

$ ./struct --ler
a = 246
b = 999
c = 735

0

Well, if the data can be visible, you can use a TXT file to allocate the data and access it later.

Here are the basics for using text file manipulation: Archives - PUCRS

Or you can use a database (mysql, oracle, etc.) for better file security and organization (if the data is larger).

Only use Text file if it is volatile data (such as an accumulator) and with little information.

Well, I hope I helped.

  • You could make a summary of what is explained in this link. If one day the link breaks, at least your answer does not become invalid.

  • Note that if the struct in question have pointers, simply write to a file does not solve the problem. Hence begins the field of serialization object...

Browser other questions tagged

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