domingo, 1 de março de 2015

Arquivo - Pesquisa em matriz quadrada


Da mesma forma que lemos dados formatados com scanf(); também é possível fazer o mesmo
com fscanf(); fscanf( );É para o arquivo o que scanf é para o console,
esta função também pertence ao arquivo de cabeçalho stdio.h.
A sintaxe da função fscanf é:
int fscanf ( FILE *arq, variável );
Bons programadores evitam o uso desta função em seus programas, alegando que por elas trabalharem com dados ASCII e não binários ocasiona perda de desempenho e de apresentação de caracteres indesejados na saída em alguns casos, coisa que eu ainda não contemplei.
Neste código mostro como usar fscanf();para lê uma matriz quadrada de inteiros
dimensionada em 10 x 10, ainda no código coloquei um bloco permitindo uma eficiente pesquisa nos elementos inteiros do arquivo.

Salve os números no bloco comentado como matriz.txt, e coloque do lado do executável para testes.

Veja abaixo imagens do programa em execução:





Veja abaixo o código do programa:


#include <stdio.h>
#include <conio.h>
#define tam 10
void Janela5 ( ) {
     int lin, col;
     for ( lin = 0; lin <= 25; lin++ ) {
         for ( col = 0; col <= 80; col++ ) {
              gotoxy ( col, lin );
              if ( lin == 2 ) {
                   textbackground ( LIGHTBLUE );
                   printf ( " " );
              }
              if ( col == 1 ) {
                   textbackground ( LIGHTBLUE );
                   printf ( " " );
              }
              if ( lin == 25 ) {
                   textbackground ( LIGHTBLUE );
              }
              if ( col == 80 ) {
                   textbackground ( LIGHTBLUE );
                   printf ( " " );
              }
         }
     }
     textbackground ( BLACK );
}
int Imp_Matr ( char *num ) {
     unsigned int i;
     for ( i = 0; i < strlen ( num ); i++ ) {
         if ( num [ i ] < '0' || num [ i ] > '9' )
              return 0;
     }
     return 1;
}
int main ( ) {
     /*
      36 48 34 89 25 56 1 59 12 81
      15 22 65 17 91 6 11 93 26 54
      85 8 35 24 39 27 76 14 21 99
      66 95 87 69 100 51 20 18 71 46
      33 45 57 67 80 50 4 82 83 92
      31 13 94 16 47 10 61 63 74 60
      5 88 37 77 23 38 86 43 72 78
      70 98 73 52 42 28 68 3 41 75
      58 79 84 97 64 55 9 19 7 32
      44 62 90 53 40 30 96 29 2 49
      */
     system ( "title ARQUIVO - PESQUISA EM MATRIZ QUADRADA" );
     int matriz [ tam ] [ tam ];
     int i, j, n;
     char num [ 3 ];
     FILE *arq = fopen ( "matriz.txt", "r" );
     if ( arq == NULL ) {
         textcolor ( YELLOW );
         gotoxy ( 26, 12 );
         printf ( "Problemas na abertura do arquivo " );
         getche ( );
         return ( 0 );
     }
     do {
         system ( "cls" );
         Janela5 ( );
         textcolor ( LIGHTRED );
         gotoxy ( 26, 3 );
         printf ( "ARQUIVO - PESQUISA EM MATRIZ QUADRADA" );
         textcolor ( LIGHTGREEN );
         gotoxy ( 26, 5 );
         printf ( "Abaixo a matriz lida por um arquivo txt" );
         textcolor ( WHITE );
         for ( i = 0; i < tam; i++ ) {
              gotoxy ( 18, i + 10 );
              for ( j = 0; j < tam; j++ ) {
                   fscanf ( arq, "%3d", &matriz [ i ] [ j ] );
                   printf ( " %3d ", matriz [ i ] [ j ] );
              }
         }
         textcolor ( LIGHTBLUE );
         gotoxy ( 26, 7 );
         printf ( "Digite um Número " );
         printf ( "para pesquisar " );
         gotoxy ( 26, 8 );
         printf ( "ou [ -1 ] para sair " );
         textcolor ( LIGHTRED );
         gets ( num );
         fflush ( stdin );
         n = atoi ( num );
         if ( n == -1 ) {
              textcolor ( LIGHTRED );
              gotoxy ( 36, 23 );
              printf ( "MUITO OBRIGADO" );
              getche ( );
              exit ( 0 );
         }
         if ( n < 0 ) {
              textcolor ( LIGHTBLUE );
              gotoxy ( 26, 21 );
              printf ( "\aO único negativo válido é o " );
              textcolor ( LIGHTRED );
              printf ( "-1" );
              Sleep ( 1800 );
         }
         if ( n > 100 ) {
              textcolor ( LIGHTBLUE );
              gotoxy ( 26, 22 );
              printf ( "\aO número " );
              textcolor ( LIGHTRED );
              printf ( "%d", n );
              textcolor ( LIGHTBLUE );
              printf ( " não existe na Matriz" );
              Sleep ( 1800 );
              system ( "cls" );
         }
         if ( Imp_Matr ( num ) == 0 || n == 0 ) {
              textcolor ( LIGHTBLUE );
              gotoxy ( 36, 22 );
              printf ( "\aVocê digitou " );
              textcolor ( LIGHTRED );
              printf ( "%s", num );
              Sleep ( 1800 );
              textcolor ( LIGHTBLUE );
              gotoxy ( 36, 23 );
              printf ( "\aNão foi aceito" );
              Sleep ( 1800 );
         } else {
              textcolor ( LIGHTBLUE );
              gotoxy ( 18, 9 );
              for ( i = 0; i < tam; i++ ) {
                   for ( j = 0; j < tam; j++ ) {
                        if ( n == matriz [ i ] [ j ] ) {
                            textcolor ( LIGHTBLUE );
                            textcolor ( LIGHTBLUE );
                            gotoxy ( 20, 21 );
                            printf ( "O valor " );
                            textcolor ( LIGHTRED );
                            printf ( "%d", n );
                            textcolor ( LIGHTBLUE );
                            printf ( " foi encontrado na linha " );
                            textcolor ( LIGHTRED );
                            printf ( "%d", i );
                            textcolor ( LIGHTBLUE );
                            printf ( " e coluna " );
                            textcolor ( LIGHTRED );
                            printf ( "%d ", j );
                            Sleep ( 1800 );
                            textcolor ( LIGHTRED );
                            gotoxy ( 33, 23 );
                            printf ( "PRESSIONE QUALQUER TECLA" );
                            getche ( );
                        }
                   }
              }
         }
     } while ( 1 );
     fclose ( arq );
     textcolor ( LIGHTRED );
     gotoxy ( 35, 21 );
     printf ( "O ROCCO AGRADECE" );
     getche ( );
     return 0;

}


Nenhum comentário:

Postar um comentário

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