Thread: Errors with struct and I/O

  1. #31
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Thanks

    Already made some changes, but the code from yesterday has changed a bit since i had several warning that i have removed.

    This is my last code with the change you ask me to do.

    Code:
    /*
     ============================================================================
     Name        : Trabalho.c
     Author      : gmc
     Version     : 1.0
     Copyright   : GMC
     Description : Buzz
     ============================================================================
     */
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    
    void ad_perguntas();
    void ver_perguntas();
    void estrelas();
    void menu_principal();
    void jogo();
    void menu_ad();
    void adm();
    void main();
    
    
    
    
    //******************************************************************************************************
    //Estruturas a serem usadas
    
    
    struct perg           /* Estrutura Questões */
    {
      int id;
      char ques[200];
      char op1[15];
      char op2[15];
      char op3[15];
      char op4[15];
      int res;
    };
    
    
    struct jogador 			 /* Estrutura Utilizadores */
    {
      char nome[100];
      char id[100];
      char pass[100];
      int log;
    };
    
    
    //função para adcionar perguntas num ficheiro
    void ad_perguntas()
    {
    	struct perg per[100];
    	int quantos;
    	char tmp[200];
    	char *p;
    	printf("Quantos registos quer criar? ");
    	fgets(tmp, sizeof tmp, stdin);
    	quantos=strtol(tmp, NULL, 10);
    	int n;
    	    for (n = 0; n < quantos; n++)
    	    {
    	    	printf("Introduza ID para a pergunta: \n");
    	    	fgets(tmp, sizeof tmp, stdin);
    	    	per[n].id = strtol(tmp, NULL, 10);
    	    	printf("Introduza a pergunta: \n");
    	    	fgets(per[n].ques, 200, stdin);
    	    	 if ((p = strchr(per[n].ques, '\n')) != NULL)
    	    	*p = '\0';
    	    	printf("Opção 1 : \n");
    	    	fgets(per[n].op1, 14, stdin);
    	    	 if ((p = strchr(per[n].op1, '\n')) != NULL)
    	    	*p = '\0';
    	    	printf("Opção 2 :\n");
    	    	fgets(per[n].op2, 14, stdin);
    	    	 if ((p = strchr(per[n].op2, '\n')) != NULL)
    	    	*p = '\0';
    	    	printf("Opção 3 : \n");
    	    	fgets(per[n].op3, 14, stdin);
    	    	 if ((p = strchr(per[n].op3, '\n')) != NULL)
    	    	*p = '\0';
    	    	printf("Opção 4 : \n");
    	    	fgets(per[n].op4, 14, stdin);
    	    	 if ((p = strchr(per[n].op4, '\n')) != NULL)
    	    	*p = '\0';
    	    	printf("Introduza o número da resposta correta: \n");
    	    	fgets(tmp, sizeof tmp, stdin);
    	    	per[n].res = strtol(tmp, NULL, 10);
    
    
    }
    	    FILE* data;
    	       if ( (data = fopen("data.txt", "a")) == NULL )
    	       {
    	           printf("Erro \n");
    	       }
    	       for (n = 0; n < quantos; n++) {
    	           fprintf(data, "%d - %s %s|%s|%s|%s|Resposta correta: %d \n",per[n].id, per[n].ques, per[n].op1, per[n].op2, per[n].op3, per[n].op4, per[n].res);
    	           adm();
    	       }
    	      fclose(data);
    	   }
    
    
    void ver_perguntas()
    {
    	{
    char c;
    	    FILE* data;
    	    if ((data = fopen("data.txt", "rb")) == NULL)
    	    {
    	        printf("Erro ao abrir ficheiro\n");
    	    }
    	    struct perg* per;
    	    per= malloc(100 * sizeof(*per));
    	    fread(per[0].ques, sizeof(struct perg), 100, data);
    	    free(per);
    	    fclose(data);
    	    printf("Quer voltar ao menu anterior? \n");
    	    scanf("%c", &c);
    	    if (c=='s'||c=='S')
    	    {
    	    	menu_ad();
    	    }
    	}
    }
    //Funções a serem usadas
    void estrelas()
    {
    	int i;
    	for (i=0; i<=20; i++)
    	{
    		putchar('*');
    	}
    	//Poe caracter vazio
    	putchar('\n');
    }
    
    
    void menu_principal()
    {
    
    
    	int op;
    	//Escreve string
    		puts("------------MENU-------------------\n");
    		printf("1 - Entrar como Administador \n");
    		printf("2 - Entrar como jogador \n");
    		printf("3 - Sair da aplicação \n");
    		printf("Escolha uma das opções:\n");
    		scanf("%d", &op);
    
    
    				switch (op)
    				{
    				case 1:
    					//chama função admin
    					adm();
    					break;
    				case 2:
    					//chama estrutura 2
    					jogo();
    					break;
    				case 3:
    						//chama estrutura 3
    					exit(0);
    					break;
    				default:
    					printf("Opção inválida");
    				}
    }
    void jogo()
    {
    	int op1;
    	    printf("1 - Jogo curto (2 perguntas)\n");
    		printf("2 - Jogo médio (4 perguntas)\n");
    		printf("3 - Jogo longo (8 perguntas)\n");
    		printf("4 - Voltar ao menu inicial \n");
    		printf("Escolha o tipo de jogo desejado:\n");
    		scanf("%d", &op1);
    
    
    		switch (op1)
    		{
    		case 1:
    			//chama estrutura 1
    			printf("escolheu 1");
    			break;
    		case 2:
    			//chama estrutura 2
    			printf("escolheu 2");
    			break;
    		case 3:
    			//chama estrutura 3
    			printf("escolheu 3");
    			break;
    		case 4:
    				//chama estrutura 3
    				menu_principal();
    				break;
    		default:
    			printf("Valor inválido");
    		}
    }
    
    
    void menu_ad()
    {
        int op;
        printf("1 - Inserir perguntas na BD \n");
        printf("2 - Ver perguntas da BD \n");
        scanf("%d", &op);
        getchar();
        switch (op)
        {
        case 1:
            ad_perguntas();
            break;
        case 2:
            ver_perguntas();
        default:
            printf("Escolha inválida \n");
        }
    }
    void adm()
    {
    	char login [10], pass [10];
    	int x, a=1 , b=1;
    	for (x=0; x<3; x++)
    	{
    		printf("Utilizador: \n");
            scanf("%s", login);
    		printf("Password: \n");
    		scanf("%s", pass);
    		a= strcmp(login,"gil");
    		b= strcmp(pass, "123");
    		if (a==0 && b==0)
    		{
    			printf("Bem vindo \n");
    			//Chamar um menu de escolha para o Admin
    			menu_ad();
    			x=5;
    			break;
    		}
    		else
    		{
    			printf("Dados Utilizador ou Pass errados....Tente de novo \n");
    		}
    	}
    	if (x==3)
    	{
    	printf("Tentativas exedidas, vai voltar ao menu inicial..\n");
    	menu_principal();
    	}
    }
    
    
    
    
    void main()
    {
    	estrelas();
    	printf("BEMVINDOS AO BUZZ \n");
    	estrelas();
    	putchar('\n');
    	menu_principal();
    
    
    }
    1- Nothing is writed when i use ad_perguntas function.

    2- I can't read anything with ver_perguntas function

    3- I have only one warning in the end

    Description Resource Path Location Type
    return type of ‘main’ is not ‘int’ [-Wmain]

    When i get something to work....other one stops working

  2. #32
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    1 - When I ran your program, it wrote information to data.txt. There were some minor problems, but it worked 90%. What exact input are you giving it? Copy-paste your terminal session in a post here.
    2 - Nor can I, but I don't understand what the program is saying since I don't know Portuguese.
    3 - This is easy. The correct way to declare main is int main(). You never need a prototype for main, so remove it.

    After we get these problems fixed, there's a few more problems to deal with: your menus all call each other recursively. That is, menu_principal calls adm, which then calls menu_principal again. If you continue to run your program for a long time, it will crash. You should use a loop for each menu:
    Code:
    do {
        print menu choices
        // 1 - insert question
        // 2 - view questions
        // 3 - return to main menu
        read choice
        switch choice
            case 1:
                insert_question()
            case 2:
                print_questions()
            case 3:
                // do nothing
            default:
                print "invalid choice"
    } while (choice != 3);
    Something like that. But wait until we fix the other problems first.

  3. #33
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Thanks again.

    Well, it's strange since mine data.txt still empty

    whell my inputs are the following (translated)

    Bem vindo (Welcome)
    1 - Inserir perguntas na BD (Insert questions in Database)
    2 - Ver perguntas da BD (See questions in Database)
    1
    Quantos registos quer criar? 1 (Records you want to add)
    Introduza ID para a pergunta: (Id insert
    1
    Introduza a pergunta: (Insert question)
    Melhor clube do mundo?
    Opção 1 : //Options 1 to 4
    Benfica
    Opção 2 :
    Real Madrid
    Opção 3 :
    Barcelona
    Opção 4 :
    Bayern
    Introduza o número da resposta correta: (Insert the right choice)
    1

    After checking my data.txt, i see no inputs there

    Don't understand how does it works for you.

    I'm using Eclipse IDE C/C++ for linux

    regards

  4. #34
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    Perhaps because you are using Eclipse, it is running your program in a special folder, maybe a debug or release folder, and you are looking an an old data.txt that isn't correct. Check the time on the data.txt you're looking at and make sure it matches the current time when you ran your program, to make sure you're looking at the right file. I don't use Eclipse, so I can't help you any more than that.

    As for your ver_perguntas function, you have a big problem. You open the file in binary mode ("rb") and read in binary data (fread is for binary data). But when you wrote the file in ad_perguntas, you wrote it in text mode, using fprintf. You should use fscanf to read the data back, but you need use a | to separate the question from the answers in ad_perguntas (scanf is easily confused by spaces between words, so it's best not to separate fields with spaces).
    Code:
    fprintf(data, "%d - %s|%s|%s|%s|%s|Resposta correta: %d \n",per[n].id, per[n].ques, per[n].op1, per[n].op2, per[n].op3, per[n].op4, per[n].res);
    ...
    data = fopen("data.txt", "r");  // no "b", since not binary mode
    // check if fopen failed
    fscanf(data, "%d - %[^|]|%[^|]|...|Reposta correta: %d", &per[n].id, per[n].ques, per[n].op1, ..., &per[n].res)
    Notice that scanf requires the address of the place to store the data, which is why I use the & in front of integers. The strings (char arrays) don't need it, since the name of the array is a pointer to it's first element. Also, the %[^|] matches sets of characters. The ^ at the beginning says "not any of the following characters", so this matches everything except the "pipe" character, |

  5. #35
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Hi

    Well if it does work with you it's must be my eclipse..

    I have deleted the data.txt, recompile the program and ran it and still empty

    created : Ter 24 Abr 2012 19:40:53 WEST

    0 bytes

    Code:
    void ver_perguntas()
    {
    	{
    char c;
    int n;
    	    FILE* data;
    	    if ((data = fopen("data.txt", "r")) == NULL)
    	    {
    	        printf("Erro ao abrir ficheiro\n");
    	    }
    	    struct perg* per;
    	    per= malloc(100 * sizeof(*per));
    	    fscanf(data, "%d - %[^|]|%[^|]|%[^|]|%[^|]|%[^|]Resposta correta: %d", &per[n].id, per[n].ques, per[n].op1, per[n].op2,per[n].op3, per[n].op4, &per[n].res);
    	    fclose(data);
    	    printf("Quer voltar ao menu anterior? \n");
    	    scanf("%c", &c);
    	    if (c=='s'||c=='S')
    	    {
    	    	menu_ad();
    	    }
    	}
    }
    Now i have 1 warning in fscanf

    n’ is used uninitialized in this function [-Wuninitialized]

    I understand why, because the n was the loop in the ad_perguntas function but it is necessary to use it here? Iv'e tried to remove it ut then i have several errors about structures variables...

    Wich compiler do you use??

  6. #36
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    Sorry I wasn't very clear. I'm confused on what exactly your ver_perguntas function is supposed to do. Is it supposed to read all of the questions out of data.txt or just one? If it's just one, then you only need to allocate 1 perg struct and read into that:
    Code:
    per = malloc(sizeof(*per));
    fscanf(data, "...", &per->id, per->ques, ...);
    If you need to read in all of them, you should store the total number of questions as the first line of data.txt so you know how many to allocate in ver_perguntas. You would need a loop to read them, which is where n would be used:
    Code:
    // in ad_perguntas
    fprintf(data, "%d\n", quantos);
    // in ver_perguntas
    int quantos, n = 0;
    fscanf(data, "%d", &quantos);
    per = malloc(quantos * sizeof(*per));
    while (fscanf(data, "...", &per[n].id, per[n].ques, ...) == 7 && n < quantos) {
        n++;
    }
    I put n < quantos in the for loop to avoid going past the end of the array. fscanf returns the number of things it successfully read in. You want to keep running your loop until it doesn't read in a full question, which should happen when you reach the end of file.

  7. #37
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Hi

    ver_perguntas is a function where i keep the questions, the options and correct answer.
    What i would like to do is keep a file where i have for example:

    ID Question OP1 OP2 OP3 OP4 Answer

    1 Best clube? Benfica Chelsea Madrid Barcelona 1
    2 Best player Messi Gaitan Ronaldo Ozil 3


    ...............

    Now with the ver_perguntas i can see the everything. With that, i will create a function to delete a record by the ID.

    In the ad_perguntas function i use id variable but i must implement a condition
    Code:
    if (id == id1)
    {
    printf("This id is already in use, try another one");
    }
    Still i must put the code you send me in my file??

    regards and really thanks for all your help

  8. #38
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    Okay, so ver_perguntas needs to print out everything in the file. For that, you only need one perg struct, and you don't need to use malloc:
    Code:
    struct perg per;  // note, not a pointer, an actual struct
    fp = open data file
    if fp is NULL
        print error and return from function
    while (fscanf(fp, "...", &per.id, per.ques, ..., &per.res) == 7)  // scanf returns the number of items "scanned", if it's not all 7 things you asked for, it's an error
        print out the information in per: per.id, per.ques, etc
    fclose(fp);

  9. #39
    Registered User
    Join Date
    Apr 2012
    Posts
    154

    Nothing

    Hi

    I've made changes but now in void ad_perguntas i have a strange issue:

    After putting the ID the question "Introduza pergunta" and 1ª opção comes together and it can't be like this because the user must input data in both of them.

    Code:
    /*
     ============================================================================
     Name        : Trabalho.c
     Author      : gmc
     Version     : 1.0
     Copyright   : GMC
     Description : Buzz
     ============================================================================
     */
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    
    void ad_perguntas();
    void ver_perguntas();
    void estrelas();
    void menu_principal();
    void jogo();
    void menu_ad();
    void adm();
    int main();
    
    
    
    
    
    
    //******************************************************************************************************
    //Estruturas a serem usadas
    
    
    struct perg           /* Estrutura Questões */
    {
      int id;
      char ques[200];
      char op1[15];
      char op2[15];
      char op3[15];
      char op4[15];
      int res;
    };
    
    
    struct jogador 			 /* Estrutura Utilizadores */
    {
      char nome[100];
      char id[100];
      char pass[100];
      int log;
    };
    
    
    //função para adcionar perguntas num ficheiro
    void ad_perguntas()
    {
        FILE *f= fopen("perguntas", "w+b");
    	struct perg p;
    	    printf("Introduza o ID da pergunta \n");
    	    scanf("%d", &p.id);
    	    printf("Introduza a pergunta: \n");
    	    gets(p.ques);
    	    fflush(stdin);
    	    printf("1ª Opcao:  \n");
    	    gets(p.op1);
    	    printf("2ª Opcao:  \n");
    	    gets(p.op2);
    	    printf("3ª Opcao:  \n");
    	    gets(p.op3);
    	    printf("4ª Opcao:  \n");
    	    gets(p.op4);
    	    printf("Introduza numero da resposta certa \n");
    	    scanf("%d", &p.res);
    	    fwrite(&p, sizeof(struct perg), 100 , f);
    	    rewind(f);
    	}
    
    
    void ver_perguntas()
    {
    
    
    FILE *f= fopen("perguntas", "r+b");
    	struct perg p1;
    	fwrite(&p1, sizeof(struct perg), 100 , f);
    	printf("Id: \n", &p1.id);
    	printf("Pergunta: \n",p1.ques);
    	printf("Opcao 1: \n", p1.op1);
    	printf("Opcao 2: \n", p1.op2);
    	printf("Opcao 3: \n", p1.op3);
    	printf("Opcao 4: \n", p1.op4);
    	printf("Correto: \n", &p1.res);
    	fclose(f);
    
    
    }
    //Funções a serem usadas
    void estrelas()
    {
    	int i;
    	for (i=0; i<=20; i++)
    	{
    		putchar('*');
    	}
    	//Poe caracter vazio
    	putchar('\n');
    }
    void menu_principal()
    {
    	int op;
    	//Escreve string
    		puts("------------MENU-------------------\n");
    		printf("1 - Entrar como Administador \n");
    		printf("2 - Entrar como jogador \n");
    		printf("3 - Sair da aplicação \n");
    		printf("Escolha uma das opções:\n");
    		scanf("%d", &op);
    
    
    				switch (op)
    				{
    				case 1:
    					//chama função admin
    					adm();
    					break;
    				case 2:
    					//chama estrutura 2
    					jogo();
    					break;
    				case 3:
    						//chama estrutura 3
    					exit(0);
    					break;
    				default:
    					printf("Opcao invalida");
    				}
    }
    void jogo()
    {
    	int op1;
    	do
    	{
    	    printf("1 - Jogo curto (2 perguntas)\n");
    		printf("2 - Jogo medio (4 perguntas)\n");
    		printf("3 - Jogo longo (8 perguntas)\n");
    		printf("4 - Voltar ao menu inicial \n");
    		printf("Escolha o tipo de jogo desejado:\n");
    		scanf("%d", &op1);
    
    
    		switch (op1)
    		{
    		case 1:
    			//chama estrutura 1
    			printf("escolheu 1");
    			break;
    		case 2:
    			//chama estrutura 2
    			printf("escolheu 2");
    			break;
    		case 3:
    			//chama estrutura 3
    			printf("escolheu 3");
    			break;
    		case 4:
    				//chama estrutura 3
    				menu_principal();
    				break;
    		default:
    			printf("Valor invalido");
    		}
    	}while (op1<=5);
    		getchar();
    }
    void menu_ad()
    	{
    	  int x;
    	  do {
    		  printf("1 - Inserir perguntas: \n");
    		  printf("2 - Ver as perguntas: \n");
    	    scanf("%d", &x);
    	    getchar();
    	    switch (x)
    	    {
    	    case 1:
    	    	ad_perguntas();
    	    	break;
    	    case 2:
    	    	ver_perguntas();
    	    	break;
    	    case 3:
    	    	//não faz nada
    	    	break;
    	    default:
    	    	printf("Escolha inválida");
    	    }
    	  } while ( x != 3 );
    	}
    void adm()
    {
    	char login [10], pass [10];
    	int x, a=1 , b=1;
    	for (x=0; x<3; x++)
    	{
    		printf("Utilizador: \n");
            scanf("%s", login);
    		printf("Password: \n");
    		scanf("%s", pass);
    		a= strcmp(login,"gil");
    		b= strcmp(pass, "123");
    		if (a==0 && b==0)
    		{
    			printf("Bem vindo \n");
    			//Chamar um menu de escolha para o Admin
    			menu_ad();
    			x=5;
    			break;
    		}
    		else
    		{
    			printf("Dados Utilizador ou Pass errados....Tente de novo \n");
    		}
    	}
    	if (x==3)
    	{
    	printf("Tentativas exedidas, vai voltar ao menu inicial..\n");
    	menu_principal();
    	}
    }
    int main()
    {
    	estrelas();
    	printf("BEMVINDOS AO BUZZ \n");
    	estrelas();
    	putchar('\n');
    	menu_principal();
    
    
    }
    Do you know why?

    regards

  10. #40
    Registered User
    Join Date
    May 2010
    Posts
    4,552
    Code:
            scanf("%d", &p.id);
            printf("Introduza a pergunta: \n");
            gets(p.ques);
            fflush(stdin);
    Please read these links:
    gets()
    fflush(stdin)

    Do you know why?
    Yes, scanf() is leaving the end of line character in your input buffer, you must remove this character before you try to retrieve a character or C-string.

    Jim

  11. #41
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Thanks Jim

    Already resolved that issue, the function void ad_perguntas is wroking correctly now.
    The issues now is the ver_perguntas issue.
    I want him to print all records from the perguntas file and when i'm running the program it says

    0 questions.

    Code:
    void ver_perguntas()
    {
    int retorno, cont = 0;
    struct perg p;
    FILE *f= fopen("perguntas", "r");
    
    
    retorno= fread(&p, sizeof(struct perg), 1 , f);
       clrscr();
       while ( retorno == 1) {
       cont++;
        printf("\n\n Perguntas na BD %d \n", cont);
    	printf("Id: \n",&p.id);
    	printf("Pergunta: \n",p.ques);
    	printf("Opcao 1: \n",p.op1);
    	printf("Opcao 2: \n",p.op2);
    	printf("Opcao 3: \n",p.op3);
    	printf("Opcao 4: \n",p.op4);
    	printf("Correto: \n",&p.res);
    	retorno= fread(&p, sizeof(struct perg), 1 , f);
       }
        printf(" \n\n %d perguntas registadas ", cont);
       getch();
    }
    Is there anything wrong in here??


    regards and thanks

  12. #42
    Registered User
    Join Date
    May 2010
    Posts
    4,552
    Are you sure your file opened correctly? You should always check if the file opened correctly. If your first read fails only "0 perguntas registadas" should printout.

    Jim

  13. #43
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Hi

    I'm sure it open because i've tried with an if statement and says file open

    But the strange now is nothing is writed....

    Code:
    /* 
     ============================================================================ 
     Name        : Trabalho.c 
     Author      : gmc 
     Version     : 1.0 
     Copyright   : GMC 
     Description : Buzz 
     ============================================================================ 
     */ 
     
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 
    #include <ctype.h> 
     
    void ad_perguntas(); 
    void ver_perguntas(); 
    void estrelas(); 
    void menu_principal(); 
    void jogo(); 
    void menu_ad(); 
    void adm(); 
    int main(); 
     
     
     
    //****************************************************************************************************** 
    //Estruturas a serem usadas 
     
    struct perg           /* Estrutura Questões */ 
    { 
      int id; 
      char ques[200]; 
      char op1[15]; 
      char op2[15]; 
      char op3[15]; 
      char op4[15]; 
      int res; 
    }; 
     
    struct jogador              /* Estrutura Utilizadores */ 
    { 
      char nome[100]; 
      char id[100]; 
      char pass[100]; 
      int log; 
    }; 
     
    //funcao para adcionar perguntas num ficheiro 
    void ad_perguntas() 
    { 
        struct perg p; 
        FILE *f= fopen("perguntas", "wb"); 
        if ((f == NULL)) 
            { 
            printf("Erro na abertura do ficheiro."); 
            } 
            else{ 
    //Lê do teclado e grava no ficheiro 
            printf("Introduza o ID da pergunta \n"); 
            scanf("%c",&p.id); 
            fflush(stdin); 
            if (p.id != 0) 
            { 
            printf("Introduza a pergunta: \n"); 
            fgets(p.ques,200, stdin); 
            printf("Opcao 1:  \n"); 
            fgets(p.op1, 15, stdin); 
            printf("Opcao 2:  \n"); 
            fgets(p.op2, 15, stdin); 
            printf("Opcao 3:  \n"); 
            fgets(p.op3, 15, stdin); 
            printf("Opcao 4:  \n"); 
            fgets(p.op4, 15, stdin); 
            printf("Introduza numero da resposta certa \n"); 
            scanf("%d", &p.res); 
            fwrite(&p, sizeof(struct perg), 100 , f); 
     
            rewind(f); 
            } 
            } 
        } 
     
    void ver_perguntas() 
    { 
    int retorno, cont = 0; 
    struct perg p; 
    FILE *f= fopen("perguntas", "rb"); 
     if ((f == NULL)) 
            { 
            printf("Erro na abertura do ficheiro."); 
            } 
     
    retorno= fread(&p, sizeof(struct perg), 1 , f); 
       clrscr(); 
       while ( retorno == 1) { 
       cont++; 
        printf("\n\n Perguntas na BD %d \n", cont); 
        printf("Id: %d \n",&p.id); 
        printf("Pergunta: %s \n",p.ques); 
        printf("Opcao 1: %s \n",p.op1); 
        printf("Opcao 2: %s \n",p.op2); 
        printf("Opcao 3: %s \n",p.op3); 
        printf("Opcao 4: %s \n",p.op4); 
        printf("Correto: %d \n",&p.res); 
        retorno= fread(&p, sizeof(struct perg), 1 , f); 
       } 
        printf(" \n\n %d perguntas registadas ", cont); 
       getch(); 
    } 
    //Funcoes a serem usadas 
    void estrelas() 
    { 
        int i; 
        for (i=0; i<=20; i++) 
        { 
            putchar('*'); 
        } 
        //Poe caracter vazio 
        putchar('\n'); 
    } 
    void menu_principal() 
    { 
        int op; 
        //Escreve string 
            puts("------------MENU-------------------\n"); 
            printf("1 - Entrar como Administador \n"); 
            printf("2 - Entrar como jogador \n"); 
            printf("3 - Sair da aplicação \n"); 
            printf("Escolha uma das opções:\n"); 
            scanf("%d", &op); 
     
                    switch (op) 
                    { 
                    case 1: 
                        //chama função admin 
                        adm(); 
                        break; 
                    case 2: 
                        //chama estrutura 2 
                        jogo(); 
                        break; 
                    case 3: 
                            //chama estrutura 3 
                        exit(0); 
                        break; 
                    default: 
                        printf("Opcao invalida"); 
                    } 
    } 
    void jogo() 
    { 
        int op1; 
        do 
        { 
            printf("1 - Jogo curto (2 perguntas)\n"); 
            printf("2 - Jogo medio (4 perguntas)\n"); 
            printf("3 - Jogo longo (8 perguntas)\n"); 
            printf("4 - Voltar ao menu inicial \n"); 
            printf("Escolha o tipo de jogo desejado:\n"); 
            scanf("%d", &op1); 
     
            switch (op1) 
            { 
            case 1: 
                //chama estrutura 1 
                printf("escolheu 1"); 
                break; 
            case 2: 
                //chama estrutura 2 
                printf("escolheu 2"); 
                break; 
            case 3: 
                //chama estrutura 3 
                printf("escolheu 3"); 
                break; 
            case 4: 
                    //chama estrutura 3 
                    menu_principal(); 
                    break; 
            default: 
                printf("Valor invalido"); 
            } 
        }while (op1<=5); 
            getchar(); 
    } 
    void menu_ad() 
        { 
          int x; 
          do { 
              printf("1 - Inserir perguntas: \n"); 
              printf("2 - Ver as perguntas: \n"); 
            scanf("%d", &x); 
            getchar(); 
            switch (x) 
            { 
            case 1: 
                ad_perguntas(); 
                break; 
            case 2: 
                ver_perguntas(); 
                break; 
            case 3: 
                //não faz nada 
                break; 
            default: 
                printf("Escolha inválida"); 
            } 
          } while ( x != 3 ); 
        } 
    void adm() 
    { 
        char login [10], pass [10]; 
        int x, a=1 , b=1; 
        for (x=0; x<3; x++) 
        { 
            printf("Utilizador: \n"); 
            scanf("%s", login); 
            printf("Password: \n"); 
            scanf("%s", pass); 
            a= strcmp(login,"gil"); 
            b= strcmp(pass, "123"); 
            if (a==0 && b==0) 
            { 
                printf("Bem vindo \n"); 
                //Chamar um menu de escolha para o Admin 
                menu_ad(); 
                x=5; 
                break; 
            } 
            else 
            { 
                printf("Dados Utilizador ou Pass errados....Tente de novo \n"); 
            } 
        } 
        if (x==3) 
        { 
        printf("Tentativas exedidas, vai voltar ao menu inicial..\n"); 
        menu_principal(); 
        } 
    } 
    int main() 
    { 
        estrelas(); 
        printf("BEMVINDOS AO BUZZ \n"); 
        estrelas(); 
        putchar('\n'); 
        menu_principal(); 
    system("pause"); 
    return 0; 
    }
    Any reason??

    Regards

  14. #44
    Registered User
    Join Date
    Oct 2001
    Posts
    62
    Code:
    if ((data = fopen("data.txt", "rb")) == NULL)
    {
        printf("Erro ao abrir ficheiro\n");
    }
    If the file could not be opened, you print a message and... continue to read as though nothing had happened...

    The output of printf() is usually buffered. You do not see the message because your program crashes before the buffer is flushed.
    That's why error messages should be sent to (unbuffered) stderr:

    Code:
    fprintf(stderr, "Erro...");
    Last edited by rpet; 05-10-2012 at 10:02 AM. Reason: added some more info about buffered output

  15. #45
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Hi

    The file is open now but when i use ther ver_perguntas function where is going to print all my questions he gives me this:

    Perguntas na BD 30
    Id: -902882736
    Pergunta:
    Opcao 1:
    Opcao 2:
    Opcao 3:
    Opcao 4:
    Correto: -902882472

    Instead of the id 01, he gives me a memory adress, the same with correto

    The rest comes empty...why??

    regards

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 03-06-2011, 09:12 PM
  2. struct holding data inside a linked list struct
    By icestorm in forum C Programming
    Replies: 2
    Last Post: 10-06-2009, 12:49 PM
  3. Making a (atom) class in a (struct) class makes big errors!
    By Yarin in forum Windows Programming
    Replies: 4
    Last Post: 09-11-2007, 07:18 PM
  4. Script errors - bool unrecognized and struct issues
    By ulillillia in forum Windows Programming
    Replies: 10
    Last Post: 12-18-2006, 04:44 AM
  5. Struct errors...
    By Cale in forum C Programming
    Replies: 2
    Last Post: 12-12-2002, 11:49 PM