Retrieve struct data in C

0

How do I save a Struct to a C file and retrieve this data in another program's execution?

    
asked by anonymous 12.07.2017 / 16:04

2 answers

0

Here's an illustrative (tested) example of how to read and write data from a struct to 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

Testing reading:

$ ./struct --ler
a = 246
b = 999
c = 735
    
12.07.2017 / 21:02
0

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

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

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

Use only the text file if it is volatile data (such as an accumulator, for example) and with little information.

Well, I hope I have helped.

    
12.07.2017 / 16:16