Fscanf, fprintf and printf

Asked

Viewed 576 times

0

I have a problem with reading and showing on screen. The program it read from the keyboard a series of data, save them in a binary file and then allow the query of how this information is in the bin file, showing them on the screen;

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


int main(int argc, char **argv)
{

FILE *mestre, *indice;
int opcao, i=0;
int resp = 0, resp4 = 0;

/* lay-out do arquivo mestre */
struct reg_mestre
{   int posicao;
    char nome_pacote[20];
    char destino[15];
    float preco;
    int nr_dias;
    char meio_transporte[15];
 };

struct reg_mestre dados[50];

/* lay-out do arquivo de índices */
struct reg_indice
{   char nome_pacote[20];
    int posicao;
};

struct reg_indice dados2[50];

do {    

    printf ("Bem vindo ao catalogo da agência de viagens!\n");
    printf ("\nO que deseja fazer: \n");
    printf ("\n1 - Adicionar\n");
    printf ("2 - Remover\n");
    printf ("3 - Alterar\n");
    printf ("4 - Exibir todo o Catalogo\n");
    printf ("5 - Consultar um destino específico\n");

    printf("\n\nESCOLHA: ");
    scanf ("%d", &opcao);

    if (opcao == 1){

            mestre = fopen("//home//vitor//Desktop//mestre.bin", "ab");
            indice = fopen("//home//vitor//Desktop//indice.bin", "ab");

            if (mestre){  
                        i++;
                        printf ("--------------------------------------------");
                        printf ("\nPACOTE: %d\n",i); 
                        printf ("\nNome do Pacote: ");
                        __fpurge(stdin); //fflush do linux
                        fflush(stdin); 
                        gets (dados[i].nome_pacote);
                        fflush(stdin);
                        __fpurge(stdin);
                        printf ("Destino: ");
                        fflush(stdin);  
                        __fpurge(stdin);            
                        gets (dados[i].destino);
                        fflush(stdin);
                        __fpurge(stdin); 
                        printf("Preço: ");
                        scanf ("%f", &dados[i].preco);
                        __fpurge(stdin);
                        fflush(stdin); 
                        printf ("Dias: ");
                        scanf ("%d", &dados[i].nr_dias);
                        __fpurge(stdin);
                        fflush(stdin); 
                        printf ("Meios de Transporte: ");
                        __fpurge(stdin);
                        gets (dados[i].meio_transporte);
                        __fpurge(stdin);  
                        fflush(stdin);                      
                        fprintf(mestre,"%s %s %f %d %s\n",dados[i].nome_pacote, dados[i].destino, dados[i].preco, dados[i].nr_dias, dados[i].meio_transporte);
                        fprintf(indice,"%d %s\n", i, dados2[i].nome_pacote); 

                        fclose(mestre); 
                        fclose(indice);
                        printf ("Deseja fazer mais alguma operação? (1 - Sim / 0 - Não): ");
                        scanf ("%d", &resp);
                        if (resp != 0)                  
                            printf ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }

            else {

                 printf ("Erro na abertura do arquivo");
            } 

    }


    else if (opcao == 2 ){

            mestre = fopen("//home//vitor//Desktop//mestre.bin", "wb");
            indice = fopen("//home//vitor//Desktop//indice.bin", "wb");

            if (mestre){ 
                printf("Erro na abertura do arquivo");              
            }
            else {
                    printf ("Deu certo");
                }       
        }


    else if (opcao == 3 ){

            mestre = fopen("//home//vitor//Desktop//mestre.bin", "wb");
            indice = fopen("//home//vitor//Desktop//indice.bin", "wb");

            if (mestre){ 
                printf("Erro na abertura do arquivo");                  
            }

            else {
                    printf("O arquivo abriu!");
            }       
    }

    else if (opcao == 4){

            char ch1[20], ch2[20], ch3[20];
            float fl1;
            int it1;


            mestre = fopen("//home//vitor//Desktop//mestre.bin", "rb");
            indice = fopen("//home//vitor//Desktop//indice.bin", "rb");

            if (mestre){

                while((fscanf(mestre,"%s%s%.2f%.1d%s", ch1, ch2, fl1, it1, ch3))!=EOF ){
                        printf("%s %s %f %d %s \n", ch1, ch2, fl1, it1, ch3);
                }

            }

            else {
                    printf ("O arquivo não existe ou está corrompido.\n");
                    printf ("Deseja fazer mais alguma operação? (1 - Sim / 0 - Não): ");
                    scanf ("%d", &resp4);
                    if (resp4 != 0)                 
                        printf ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }       
        }

    else if (opcao == 5){

            mestre = fopen("//home//vitor//Desktop//mestre.bin", "rb");
            indice = fopen("//home//vitor//Desktop//indice.bin", "rb");

            if (mestre){ 
                printf("Erro na abertura do arquivo");              
            }

            else {
                    printf("O arquivo abriu!");
            }       
        }
    }while (resp != 0 || resp4 != 0);

return 0;

}

The problem is how the results are shown on the screen at the end of the program, they appear like this:

Name of 0.000000 0
Package: Victor 0.000000 0
Figueredo Destination: 0.000000 0
Bahia Price: 0.000000 0
23.000000 Days: 0.000000 0
2 Half 0.000000 0
Transport: 0.000000 0
Plane Transport: 0.000000 0

Could someone explain to me why it is separating the words and what the 0.00000 signiica?

  • Are missing the & before the variables, for the fscanf function properly...

2 answers

1


I haven’t been going over your code, but I have two pieces of advice

1) Checks the result of scanf() with the number of assignments

//while((fscanf(mestre,"%s%s%.2f%.1d%s", ch1, ch2, fl1, it1, ch3))!=EOF ){
while(fscanf(mestre,"%s%s%.2f%.1d%s", ch1, ch2, fl1, it1, ch3) == 5) {
/*                                                             ^^^^ */

2) Use string size to avoid buffer overflow

//while((fscanf(mestre,"%s%s%.2f%.1d%s", ch1, ch2, fl1, it1, ch3))!=EOF ){
//while(fscanf(mestre,"%s%s%.2f%.1d%s", ch1, ch2, fl1, it1, ch3) == 5) {
while(fscanf(mestre,"%19s%19s%.2f%.1d%19s", ch1, ch2, fl1, it1, ch3) == 5) {
/*                    ^^  ^^          ^^ */

-2

Use as help this code:

int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;

pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

/* the whole file is now loaded in the memory buffer. */

// terminate
fclose (pFile);
free (buffer);
return 0;
}
  • 1

    The cool thing is to explain why your code answers the question. And in this case the author of the question is explicitly asking for it... Check [Answer].

  • Vlw brasofilo, soh gave a code to see if it helps any function to read his bin file.

  • Okis, take a hint ;)

  • It didn’t help me much, because I still don’t understand why of the 0.0000 and why of the line break. But thank you

Browser other questions tagged

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