quinta-feira, 11 de setembro de 2014

Fwrite e Fread - Matriz Float em Arquivos bin

Como nem tudo é pedreira em linguagem C, trago este bom exemplo de gravação e
leitura de uma matriz do tipo float num arquivo binário usando fwrite(); e fread();
para gravar e ler dados em arquivos binários respectivamente.
A síntaxe de fread(); é:
int fread( void *memoria, int tamanho, int quantidade, FILE *arquivo);
void *memória : é a região na qual serão armazenados os dados lidos.
int tamanho: é o número de bytes da unidade a ser lida.
int quantidade: indica quantas unidades devem ser lidas.
e no último parâmetro temos um ponteiro para o arquivo de onde
deve ser lida ou escrita uma unidade.
A função retorna o número de unidades exatamente lidas, porém poderá ser menor
que int quantidade se for encontrado o fim do arquivo ou se algum erro ocorrer.
O funcionamento de fwrite(); é muito parecido com o de fread(); só que escrevendo
no arquivo e sua síntaxe é:
int fwrite( void *memoria, int tamanho, int quantidade, FILE *arquivo);
A função retorna o número de itens escritos e este valor será igual a int quantidade
exceto se houver algum erro.

Veja uma imagem do programa em execução:



Veja abaixo o código do programa:


#include <stdio.h>
#include <conio.h>
float mat_riz [ 11 ] [ 3 ] =
       {{6.8, 14.8, 56.6},
        {9.5, 15.3, 51.8},
        {8.6, 14.8, 31.5},
        {9.7, 16.5, 75.1},
        {5.2, 17.4, 49.4},
        {7.7, 16.1, 67.9},
        {8.3, 17.5, 63.3},
        {7.3, 15.9, 47.8},
        {7.7, 16.1, 53.6},
        {4.9, 18.7, 12.4},
        {9.3, 15.9, 44.9}
};
void Janela5 ( ) {
     int lin, col;
     system ( "color F0" );
     for ( lin = 0; lin <= 36 ; lin++ ) {
         for ( col = 0; col <= 80 ; col++ ) {
              gotoxy ( col , lin );
              if ( lin == 2 ) {
                   textbackground ( BLACK );
                   printf ( " " );
              }
              if ( col == 1 ) {
                   textbackground ( BLACK );
                   printf ( " " );
              }
              if ( lin == 36 ) {
                   textbackground ( BLACK );
              }
              if ( col == 80 ) {
                   textbackground ( BLACK );
                   printf ( " " );
              }
         }
     }
     textbackground ( BLACK );
}
void Cria_Arquivo_Mat_float ( ) {
     FILE *arq;
     int l = 11;
     int c = 3;
     arq = fopen ( "C:\\Users\\SAMUEL 64SP1\\Desktop\\Arquivos\\Arquivo.bin" ,
              "wb" );
     if ( arq == NULL ) {
         printf ( "Houve um erro na criação do arquivo" );
         getche ( );
         exit ( 1 );
     }
     fwrite ( &l , sizeof(float) , 1 , arq );
     fwrite ( &c , sizeof(float) , 1 , arq );
     fwrite ( &mat_riz , sizeof ( mat_riz ) , 1 , arq );
     rewind ( arq );
     fclose ( arq );
}
void Abre_Arquivo_Mat_float ( ) {
     textbackground ( WHITE );
     FILE *arq;
     float matriz [ 11 ] [ 3 ];
     int i, j;
     int l = 11;
     int c = 3;
     arq = fopen ( "C:\\Users\\SAMUEL 64SP1\\Desktop\\Arquivos\\Arquivo.bin" ,
              "rb" );
     if ( arq == NULL ) {
         printf ( "Houve um erro na abertura do arquivo" );
         getche ( );
         exit ( 1 );
     }
     rewind ( arq );
     fread ( &l , sizeof(float) , 1 , arq );
     fread ( &c , sizeof(float) , 1 , arq );
     fread ( &matriz , sizeof ( mat_riz ) , 1 , arq );
     for ( i = 0; i < l ; i++ ) {
         gotoxy ( 35 , i + 9 );
         textcolor ( BLACK );
         for ( j = 0; j < c ; j++ )
              printf ( "%.1f " , matriz [ i ] [ j ] );
     }
     fclose ( arq );
     textcolor ( LIGHTRED );
     gotoxy ( 35 , 22 );
     printf ( "MUITO OBRIGADO" );
     getche ( );
     exit ( 0 );
}
int main ( ) {
     Janela5 ( );
     textbackground ( WHITE );
     system ( "title FWRITE E FREAD - MATRIZ FLOAT EM ARQUIVO BIN" );
     textcolor ( LIGHTRED );
     gotoxy ( 20 , 3 );
     printf ( "FWRITE E FREAD - MATRIZ FLOAT EM ARQUIVO BIN" );
     textcolor ( LIGHTMAGENTA );
     gotoxy ( 23 , 5 );
     printf ( "Programa desenvolvido por:" );
     textcolor ( BLACK );
     gotoxy ( 50 , 5 );
     printf ( "Samuel Lima" );
     textcolor ( LIGHTBLUE );
     gotoxy ( 32 , 7 );
     printf ( "sa_sp10@hotmail.com" );
     Cria_Arquivo_Mat_float ( );
     Abre_Arquivo_Mat_float ( );
}

Nenhum comentário:

Postar um comentário

Observação: somente um membro deste blog pode postar um comentário.