Thread: Error in reading from file

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    22

    Error in reading from file

    Well, i'm doing a project for my university, and i've got some mistakes, when i try to read the values from files. please someone take a look and show me possible errors. since thank.

    Code:
    #include <stdio.h>
    #include <conio.c>
    #include <time.h>
    #include <string.h>
    
    //declaração de estruturas
    typedef struct{
            float carro, moto, mensal; // definicao de preço
            int vagas_carro, vagas_moto;
            }config;  // chave desnecessaria pq o sistema lê apenas 1 registro
    typedef struct{
            char placa[9], nome[30], endereco[80], telefone[11];
            int matricula, tipo;
            }mensalistas;  // chave matricula
    typedef struct{
            char placa[9];
            int codigo, tipo, hr, min, seg, dia, mes;
            }clientes; // chave codigo
    typedef struct{
            char nome[30], endereco[80], telefone[11], funcao[20];
            int codigo;
            }funcionarios;  // chave codigo
    
    // prototipo das funções
    void principal(void); //menu principal - liga com: entrada, saida, relatorios, cadastro mensalista
    void cadastro_funcionario(void);  //tela de cadastro de funcionario
    void cadastro_mensalista(void); //tela de cadastro de mensalistas
    void login(void); // tela de login de funcionarios
    void entrada(void); // tela com o menu de entrada de veiculos
    void saida(void); // tela como o menu de saida de veiculos
    void relatorios(void); // tela de relatorios
    void ajuda(void); //menu ajuda
    void verifica(config *configuracao);//verifica configuracao
    int main(void)
    {
    //declarações
    int opcao, status;
    config configuracao, *pointer;
    //inicio
    *pointer=configuracao;
    /*Printa na tela a apresentação do programa*/
    verifica(pointer);
    printf("carro%f\n\tmoto%f\tmensal%f\n\tvaga carro%d\n\tvaga moto%d",configuracao.carro, &configuracao.moto, &configuracao.mensal, &configuracao.vagas_carro, &configuracao.vagas_moto ); //here is where i get the errors... i dunno why... plz help
    system("PAUSE");
    clrscr();
    while(opcao!=3){
        puts("******************************************\n**\tCONTROLE DE ESTACIONAMENTO\t**\n******************************************\n");
        puts("Menu Inicial:");
        gotoxy(5,6);
        puts("1 - Login");
        gotoxy(5,7);
        puts("2 - Cadastro de funcionario");
        gotoxy(5,8);
        puts("3 - Sair");
        printf("opcao escolhida: ");
        scanf("%d", &opcao);
        while((opcao<1)||(opcao>3)){
            puts("opcao invalida.\npor favor escolha novamente: ");
            scanf("%d", &opcao);
            }
        if(opcao == 1)
            login();
        if(opcao == 2)
            cadastro_funcionario();
        if(opcao == 3)
            exit(1);
        }//fim do while(opcao !=3)
        return 0;
    }//fim da main
    void principal(void){ //menu principal - liga com: entrada, saida, relatorios, cadastro mensalista
    int opcao= -1;
    while(opcao!=6){
        clrscr();
        puts("******************************************\n**\tCONTROLE DE ESTACIONAMENTO\t**\n******************************************\n");
        puts("Menu Principal:");
        gotoxy(5,6);
        puts("1 - Entrada de Veiculos");
        gotoxy(5,7);
        puts("2 - Saida de Veiculos");
        gotoxy(5,8);
        puts("3 - Relatorios");
        gotoxy(5,9);
        puts("4 - Cadastro de Mensalistas");
        gotoxy(5,10);
        puts("5 - Ajuda");
        gotoxy(5,11);
        puts("6 - Sair");
        printf("opcao escolhida: ");
        scanf("%d", &opcao);
        while((opcao<1)||(opcao>6)){
            puts("opcao invalida.\npor favor escolha novamente: ");
            scanf("%d", &opcao);
            }
        switch(opcao){
            case 1:{
                break;
                }
            case 2:{
                break;
                }
            case 3:{
                break;  
                }
            case 4:{
                break;
                }
            case 5:{
                ajuda();
                break;
                }
            case 6:{
                exit(1);
                break;
                }
            }//fim switch
    }//fim while
    
    }//fim menu principal
    void cadastro_funcionario(void){  //tela de cadastro de funcionario
    int opcao, qtd;
    char buff[80];
    puts("entrou no cadastro_funcionario");
    FILE *escrever;
    clrscr();
    fflush(stdin);
    fflush(stdout);
    funcionarios novo;
    if((escrever=fopen("cadastro.txt","a+"))==NULL){
       printf("o arquivo cadastro.txt nao pode ser aberto\no programa ira finalizar");
       system("PAUSE");
       exit(1);
       }
    else{
       //incio da captura de informações sobre o novo funcionario
       puts("por favor informe o nome do funcionario a se cadastrado");
       gets( novo.nome);
       puts("por favor informe o nome do endereco a se cadastrado");
       gets(novo.endereco);
       puts("por favor informe o telefone do funcionario a se cadastrado");
       gets(novo.telefone );
       puts("por favor informe a funcao do novo funcionario a se cadastrado");
       gets(novo.funcao);
       //fim da captura de informações sobre o novo funcionario
       //incio da rotina de salvar em arquivo
       clrscr();
       puts("estes dados estao corretos?1-Sim 2-Nao");
       printf("\tnome: %s\n\tendereco: %s\n\ttelefone: %s\n\tfuncao: %s\n\n", novo.nome, novo.endereco, novo.telefone, novo.funcao);
       scanf("%d", &opcao);
       while((opcao<1)||(opcao>2)){
         puts("opcao invalida.\npor favor escolha novamente: ");
         scanf("%d", &opcao);
         }
       if(opcao==1){
          //inicio de escrita no arquivo;uma string por linha, terminando com \n
          fprintf(escrever, "%d", qtd);
          fputs("\n", escrever);
          fputs(novo.nome, escrever);
          fputs("\n", escrever);
          fputs(novo.endereco, escrever);
          fputs("\n", escrever);
          fputs(novo.telefone, escrever);
          fputs("\n", escrever);
          fputs(novo.funcao, escrever);
          fputs("\n", escrever);
         
          puts("arquivo atualizado com sucesso\n");
          system("PAUSE");
          }//fim if(opcao==1)
          //final de escrita no arquivo
       //final da rotina de salvar em arquivo
      else{
         return;
         }
          }
    }//fim cadastro de funcionarios
    void cadastro_mensalista(void){ //tela de cadastro de mensalistas
    puts("entrou no cadastro_mensalista");
    }//fim cadastro de mensalistas
    void login(void){ // tela de login de funcionarios
    puts("entrou no login");
    FILE *ler;
    if((ler=fopen("cadastro.txt","r+"))==NULL){
       printf("o arquivo cadastro.txt nao pode ser aberto\no programa ira finalizar");
       system("PAUSE");
       exit(1);
       }
    else{
       }
    }//fim da tela de login
    void entrada(void){ // tela com o menu de entrada de veiculos
    puts("entrou na entrada");
    }//fim do menu de entrada
    void saida(void){ // tela como o menu de saida de veiculos
    puts("entrou na saida");
    }//fim do menu de saida
    void relatorios(void){ // tela de relatorios
    puts("entrou nos relatorios");
    }//fim da tela de relatorios
    void ajuda(void){ //menu ajuda
    clrscr();
    puts("1-Sobre o programa");
    system("PAUSE");
    puts("Este programa foi desenvolvido como solucao para pequenos estacionamentos com uma unica guarita.");
    puts("2-Consideracoes");
    system("PAUSE");
    puts("Este sistema e sensivel a maiusculas e minusculas, alem de nao reconhecer caracteres especiais, tais como acentos e outros");
    puts("3-Bug e Erros");
    system("PAUSE");
    puts("Pedimos a gentileza dos usuarios deste a reportar quaisquer erros e/ou bugs de versao");
    puts("4-Creditos");
    system("PAUSE");
    puts("este programa foi desenvolvido por PAULO VITOR BETTINI DE ALBUQUERQUE LIMA");
    puts("aluno devidamente matriculado na UNIVERSIDADE CATOLICA DE BRASILIA, sob a matricula, UC05059811");
    puts("tendo desenvolvido este como projeto final referente ao segundo semestre do ano de 2006");
    system("PAUSE");
    return;
    }// fim menu ajuda
    void verifica(config *configuracao){//verifica configuracao
    FILE *ler;
    FILE *escrever;
    if((ler=fopen("config.bin","rb"))==NULL){
       if((escrever=fopen("config.bin","wb"))==NULL){
           puts("erro ao criar o arquivo config.bin\no programa ira encerrar");
           system("PAUSE");
           exit(1);                                         
           }
       else{
           puts("o arquivo config.bin, nao pode ser aberto, ou nao existe,\npor favor preencha abaixo com os dados de configuracao.");
           puts("informe o preco da fracao para carros: ");
           scanf("%f", &configuracao->carro);
           puts("informe o preco da fracao para motos: ");
           scanf("%f", &configuracao->moto);
           puts("informe o preco pago por mensalistas: ");
           scanf("%f", &configuracao->mensal);
           puts("informe a quantidade de vagas disponivel para carros ");
           scanf("%d", &configuracao->vagas_carro);
           puts("informe a quantidade de vagas disponivel para motos ");
           scanf("%d", &configuracao->vagas_moto);
           fwrite(&configuracao->carro, sizeof(float),1,escrever);
           fwrite(&configuracao->moto, sizeof(float),1,escrever);
           fwrite(&configuracao->mensal, sizeof(float),1,escrever);
           fwrite(&configuracao->vagas_carro, sizeof(int),1,escrever);
           fwrite(&configuracao->vagas_moto, sizeof(int),1,escrever);
           fclose(escrever);
            }//fim escrever
       }//fim if fopen
    else{
         fread(&configuracao, sizeof(configuracao),1,ler);
         }
     fclose(ler);
    }//fim verifica

  2. #2
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    1) conio.h is non-standard so some of us can't compile your code -
    do you really need clrscr() and gotoxy()?
    2) system () is defined in stdlib.h - you'll need to include it
    3) gets is terrible (and that's being polite) - use fgets
    4) fflush (stdout) is ok, but fflush (stdin) is not - see why
    5) english is the language on this forum, so not many people will
    even look at your code because of that - i wouldn't expect you
    to translate it all because that is a lot of work, but it would be
    helpful if you highlighted the section of code causing trouble
    much more clearly
    6) problem is not well defined - what is wrong with reading from
    the files?
    7) code is poorly formatted besides

    Here's where i think the problem lies - inside the verifica function:

    Code:
    else{
         fread(&configuracao, sizeof(configuracao),1,ler);
         }
    configuracao is a struct of type config - how is fread supposed
    to be able to read into the correct members of the struct?
    remember that C is a fairly low level language - fread isn't
    designed to be able to figure out how to use structs like that.

    Without knowing what the file you are trying to read from looks
    like, i suggest the following general approach:

    use fgets to read from the file, line by line, and parse it out to
    all the members in the configuracao struct - using sscanf if
    necessary.

    this should give you an idea of what to do, hopefully i've gotten
    the ball rolling and a few more people might be able to shed
    some light on this.
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    22
    Well, sorry for the language... i'll put down here, where i think the problem is...
    if you need more code translated ask me.
    thkx
    Code:
    void verify(config *configuration){//verify the configuration of the program
    FILE *read;
    FILE *write;
    if((read=fopen("config.bin","rb"))==NULL){
       if((write=fopen("config.bin","wb"))==NULL){
           puts("there was a mistake when I tried to open config. so this program will finish");
           system("PAUSE");
           exit(1);                                         
           }
       else{
           puts("the file config.bin, cant be opened or the file doesnt exist,\nplease answer this questions.");
           puts("Set the price for CARS: ");
           scanf("%f", &configuracao->carro);
           puts("Set the price for MOTORCYCLES: ");
           scanf("%f", &configuracao->moto);
           puts("Set the price for the REGISTERED CLIENTS: ");
           scanf("%f", &configuracao->mensal);
           puts("Set the number of CARS this parking system can hold ");
           scanf("%d", &configuracao->vagas_carro);
           puts("Set the number of MOTORCYCLES this parking system can hold ");
           scanf("%d", &configuracao->vagas_moto);
           fwrite(&configuracao->carro, sizeof(float),1,escrever);
           fwrite(&configuracao->moto, sizeof(float),1,escrever);
           fwrite(&configuracao->mensal, sizeof(float),1,escrever);
           fwrite(&configuracao->vagas_carro, sizeof(int),1,escrever);
           fwrite(&configuracao->vagas_moto, sizeof(int),1,escrever);
           fclose(escrever);
            }//end  write
       }//end read
    else{ // if the file already exists read from it
         fread(&configuracao, sizeof(configuracao),1,ler);
         }
     fclose(ler);
    }//end verify

  4. #4
    Registered User
    Join Date
    Nov 2005
    Posts
    95
    I only looked at the beging of the program.

    Look throw the code, looking for the word "Error".

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h> 
    #include <limits.h>
    #include <string.h>
    #include <time.h>
    #include <assert.h>
    #include <ctype.h>
    #include <dirent.h>
    
    typedef struct{
            float carro, moto, mensal; 
            int vagas_carro, vagas_moto;
            }config;  
    typedef struct{
            char placa[9], nome[30], endereco[80], telefone[11];
            int matricula, tipo;
            }mensalistas; 
    typedef struct{
            char placa[9];
            int codigo, tipo, hr, min, seg, dia, mes;
            }clientes; 
    typedef struct{
            char nome[30], endereco[80], telefone[11], funcao[20];
            int codigo;
            }funcionarios;  
    
    void principal(void); 
    void cadastro_funcionario(void);  
    void cadastro_mensalista(void); 
    void login(void); 
    void entrada(void); 
    void saida(void); 
    void relatorios(void); 
    void ajuda(void); 
    void verifica(config *configuracao);
    
    
    
    
    int main(void)
    {
    int opcao, status;
    config configuracao, *pointer;
    
    
    /* Error "*pointer=configuracao;" ! replace with : */
    pointer = &configuracao;
    
    verifica(pointer);
    /* Error  "&configuracao.moto" why use upersand ??
    printf("carro%f\n\tmoto%f\tmensal%f\n\tvaga carro%d\n\tvaga moto%d",
            configuracao.carro, &configuracao.moto, &configuracao.mensal, 
            &configuracao.vagas_carro, &configuracao.vagas_moto ); 
    replace with : */
    printf("carro%f\n\tmoto%f\tmensal%f\n\tvaga carro%d\n\tvaga moto%d",
            configuracao.carro, configuracao.moto, configuracao.mensal, 
            configuracao.vagas_carro, configuracao.vagas_moto ); 
    
    system("PAUSE");
    
    while(opcao!=3){
        puts("******************************************\n**\tCO  NTROLE DE ESTACIONAMENTO\t**\n******************************  ************\n");
        puts("Menu Inicial:");
        puts("1 - Login");
        puts("2 - Cadastro de funcionario");
        puts("3 - Sair");
        printf("opcao escolhida: ");
        scanf("%d", &opcao);
        while((opcao<1)||(opcao>3)){
            puts("opcao invalida.\npor favor escolha novamente: ");
            scanf("%d", &opcao);
            }
        if(opcao == 1)
            login();
        if(opcao == 2)
            cadastro_funcionario();
        if(opcao == 3)
            exit(1);
        }
        return 0;
    }
    
    
    
    void principal(void){ 
    int opcao= -1;
    while(opcao!=6){
        puts("******************************************\n**\tCO  NTROLE DE ESTACIONAMENTO\t**\n******************************  ************\n");
        puts("Menu Principal:");
        puts("1 - Entrada de Veiculos");
        puts("2 - Saida de Veiculos");
        puts("3 - Relatorios");
        puts("4 - Cadastro de Mensalistas");
        puts("5 - Ajuda");
        puts("6 - Sair");
        printf("opcao escolhida: ");
        scanf("%d", &opcao);
        while((opcao<1)||(opcao>6)){
            puts("opcao invalida.\npor favor escolha novamente: ");
            scanf("%d", &opcao);
            }
        switch(opcao){
            case 1:{
                break;
                }
            case 2:{
                break;
                }
            case 3:{
                break;  
                }
            case 4:{
                break;
                }
            case 5:{
                ajuda();
                break;
                }
            case 6:{
                exit(1);
                break;
                }
            }
    }
    
    }
    
    
    
    
    void cadastro_funcionario(void)
    {  
    int opcao, qtd;
    char buff[80];
    puts("entrou no cadastro_funcionario");
    FILE *escrever;
    fflush(stdin);
    fflush(stdout);
    funcionarios novo;
    if((escrever=fopen("cadastro.txt","a+"))==NULL){
       printf("o arquivo cadastro.txt nao pode ser aberto\no programa ira finalizar");
       system("PAUSE");
       exit(1);
       }
    else{
       puts("por favor informe o nome do funcionario a se cadastrado");
       gets( novo.nome);
       puts("por favor informe o nome do endereco a se cadastrado");
       gets(novo.endereco);
       puts("por favor informe o telefone do funcionario a se cadastrado");
       gets(novo.telefone );
       puts("por favor informe a funcao do novo funcionario a se cadastrado");
       gets(novo.funcao);
       puts("estes dados estao corretos?1-Sim 2-Nao");
       printf("\tnome: %s\n\tendereco: %s\n\ttelefone: %s\n\tfuncao: %s\n\n", novo.nome, novo.endereco, novo.telefone, novo.funcao);
       scanf("%d", &opcao);
       while((opcao<1)||(opcao>2)){
         puts("opcao invalida.\npor favor escolha novamente: ");
         scanf("%d", &opcao);
         }
       if(opcao==1){
          fprintf(escrever, "%d", qtd);
          fputs("\n", escrever);
          fputs(novo.nome, escrever);
          fputs("\n", escrever);
          fputs(novo.endereco, escrever);
          fputs("\n", escrever);
          fputs(novo.telefone, escrever);
          fputs("\n", escrever);
          fputs(novo.funcao, escrever);
          fputs("\n", escrever);
         
          puts("arquivo atualizado com sucesso\n");
          system("PAUSE");
          }
      else{
         return;
         }
          }
    }
    
    
    
    void cadastro_mensalista(void){ 
    puts("entrou no cadastro_mensalista");
    }
    
    
    void login(void){ 
    puts("entrou no login");
    FILE *ler;
    if((ler=fopen("cadastro.txt","r+"))==NULL){
       printf("o arquivo cadastro.txt nao pode ser aberto\no programa ira finalizar");
       system("PAUSE");
       exit(1);
       }
    else{
       }
    }
    
    
    void entrada(void){ 
    puts("entrou na entrada");
    }
    
    
    void saida(void){ 
    puts("entrou na saida");
    }
    
    
    void relatorios(void){ 
    puts("entrou nos relatorios");
    }
    
    
    void ajuda(void){ 
    
    puts("1-Sobre o programa");
    system("PAUSE");
    puts("Este programa foi desenvolvido como solucao para pequenos estacionamentos com uma unica guarita.");
    puts("2-Consideracoes");
    system("PAUSE");
    puts("Este sistema e sensivel a maiusculas e minusculas, alem de nao reconhecer caracteres especiais, tais como acentos e outros");
    puts("3-Bug e Erros");
    system("PAUSE");
    puts("Pedimos a gentileza dos usuarios deste a reportar quaisquer erros e/ou bugs de versao");
    puts("4-Creditos");
    system("PAUSE");
    puts("este programa foi desenvolvido por PAULO VITOR BETTINI DE ALBUQUERQUE LIMA");
    puts("aluno devidamente matriculado na UNIVERSIDADE CATOLICA DE BRASILIA, sob a matricula, UC05059811");
    puts("tendo desenvolvido este como projeto final referente ao segundo semestre do ano de 2006");
    system("PAUSE");
    return;
    }
    
    
    void verifica(config *configuracao){
    FILE *ler;
    FILE *escrever;
    if((ler=fopen("config.bin","rb"))==NULL)
       {
       if( (escrever=fopen("config.bin","wb")) ==NULL)
           {
           puts("erro ao criar o arquivo config.bin\no programa ira encerrar");
           system("PAUSE");
           exit(1);                                         
           }
       else
           {
           puts("o arquivo config.bin, nao pode ser aberto, ou nao existe,\npor favor preencha abaixo com os dados de configuracao.");
           puts("informe o preco da fracao para carros: ");
           scanf("%f", &configuracao->carro);
           puts("informe o preco da fracao para motos: ");
           scanf("%f", &configuracao->moto);
           puts("informe o preco pago por mensalistas: ");
           scanf("%f", &configuracao->mensal);
           puts("informe a quantidade de vagas disponivel para carros ");
           scanf("%d", &configuracao->vagas_carro);
           puts("informe a quantidade de vagas disponivel para motos ");
           scanf("%d", &configuracao->vagas_moto);
           /* Error 
           "fwrite(&configuracao->carro, sizeof(float),1,escrever);
           fwrite(&configuracao->moto, sizeof(float),1,escrever);
           fwrite(&configuracao->mensal, sizeof(float),1,escrever);
           fwrite(&configuracao->vagas_carro, sizeof(int),1,escrever);
           fwrite(&configuracao->vagas_moto, sizeof(int),1,escrever);"
           replace with : */
           fwrite(configuracao, sizeof(*configuracao), 1, escrever);
           fclose(escrever);
           }
       }
    else 
       {
       /* Error "fread(&configuracao, sizeof(configuracao),1,ler);"
          replace with : */
       fread(configuracao, sizeof(*configuracao),1,ler);
       fclose(ler);
       }
    
    /* Error : If you failed to open the file for reading 
               why are you closing it ???? 
     fclose(ler);
    */
    }

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    22
    Thx a lot! you helped me a lot.
    Sorry by this kind of mistakes... i think this happens cuz i'm not sleepin...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM