olá gostaria de saber como faço para gravar uma estrutura em C ?.
por exemplo : quero alimentar valores em uma estrutura e depois acessar as informações.
Estrutura em linguagem C
6 Respostas
Gravar em disco?
Só confirmando, é C mesmo ou C++?
isso mesmo gostaria de saber como posso gravar informações , para quando
acessar novamente não tenha perdido os dados.
a é em linguagem C
Se for C, use o fopen, fput, fprintf, fclose, etc. Dá uma olhada aqui:
http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html
Se for C++, use os file streams:
http://www.cplusplus.com/doc/tutorial/files.html
T
Estude o código abaixo.
#include <stdio.h>
#include <string.h>
typedef struct ABCDE {
int x;
double y;
char z[100];
} ABCDE;
void imprimir (ABCDE* ab) {
printf ("x = %d, y = %.2f, z = '%s'\n", ab->x, ab->y, ab->z);
}
int main (int argc, char *argv[]) {
ABCDE ab;
FILE *f;
FILE *g;
// preenchendo os valores da struct
ab.x = 1234;
ab.y = 3.45;
strcpy (ab.z, "teste");
// imprimindo
imprimir (&ab);
// gravando
f = fopen ("arquivo.bin", "wb");
fwrite (&ab, 1, sizeof (ab), f);
fclose (f);
// zerando, só para você ver que vai ser lido direito
ab.x = 0; ab.y = 0; strcpy (ab.z, "");
// imprimindo
imprimir (&ab);
// lendo
g = fopen ("arquivo.bin", "rb");
fread (&ab, 1, sizeof (ab), g);
fclose (g);
// imprimindo
imprimir (&ab);
}
Ele deve imprimir:
x = 1234, y = 3.45, z = 'teste'
x = 0, y = 0.00, z = ''
x = 1234, y = 3.45, z = 'teste'
#include<stdio.h>
typedef struct t_customer
{
long customer_id;
char name[64];
int age;
char gender;
} Customer;
Customer customer_table[3];
void initCustomerTable();
int main()
{
int i;
//abre o arquivo p escrita
FILE *fileCustomer = fopen( "fileCustomer.dat" , "wb" );
//inicializa com dados
initCustomerTable();
//escreve no arquivo a tabela
for( i = 0 ; i < 3 ; i++ )
{
fwrite( &(customer_table[i]) , sizeof( Customer ) , 1 , fileCustomer );
}
fclose( fileCustomer ); //fecha o arquivo
//abre o arquivo para leitura
fileCustomer = fopen( "fileCustomer.dat" , "rb" );
//le os registros e exibe na tela
for( i = 0 ; i < 3 ; i++ )
{
fread( &(customer_table[i]) , sizeof( Customer ) , 1 , fileCustomer );
printf( "%d %s %d %c\n" , customer_table[i].customer_id , customer_table[i].name,
customer_table[i].age , customer_table[i].gender );
}
fclose( fileCustomer ); //fecha o arquivo
}
void initCustomerTable()
{
//customer 0
customer_table[0].customer_id = 10;
strcpy( customer_table[0].name , "Joao" );
customer_table[0].age = 23;
customer_table[0].gender = 'M';
//customer 1
customer_table[1].customer_id = 20;
strcpy( customer_table[1].name , "Maria" );
customer_table[1].age = 19;
customer_table[1].gender = 'F';
//customer 2
customer_table[2].customer_id = 30;
strcpy( customer_table[2].name , "Ana" );
customer_table[2].age = 31;
customer_table[2].gender = 'F';
}
vai aí a minha contribuição …
Criado 26 de junho de 2008
Ultima resposta 26 de jun. de 2008
Respostas 6
Participantes 4