Simple Quiz Program( Using Binary Files)
Posted by Samath
Last Updated: April 03, 2012
#include <stdio.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
#include <iostream>

struct quiz
{
char question[45];
char a[45];
char b[45];
char c[45];
char d[45];
char answer[32];
};
void addquestion();
void takequiz();

struct stackNode {
struct quiz data;
struct stackNode *nextPtr; 
};
 typedef struct stackNode StackNode; 
 typedef StackNode *StackNodePtr; 

int isEmpty( StackNodePtr topPtr )
{
return topPtr == NULL;
}

void push( StackNodePtr *topPtr,struct quiz data )
 {
 StackNodePtr newPtr = new StackNode;
if ( newPtr != NULL ) {
newPtr->data = data;
newPtr->nextPtr = *topPtr;
*topPtr = newPtr;
}
else { /* no space available */
printf( "%d not inserted. No memory available.\n");
} /* end else */
}


int main(int argc, char *argv[])
{
int access;
 
cout<<"\n\t\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n";
    cout<<"\t\t\tPlease Select An Option:\n\n";
   cout<<"\t\t\t1 - Add Question\n";
      cout<<"\t\t\t2 - Take Quiz\n";
    cout<<"\n\t\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n";
  
cout<<"\nOption:";
    scanf("%d",&access);
    switch(access)
    {
    case 1:addquestion();
    break;
    case 2:takequiz();
    break;
    default:cout<<"\t\t\tInvalid Option\n\n";
          break;
    }
return 0;
}




void takequiz()
{

  char ans[32];
  FILE *filee;
  filee = fopen("quiz.dat", "rb");
  if(filee != NULL) 
  {
   struct quiz data;
   while(fread(&data, sizeof data, 1, filee) == 1) 
    {
    printf("\n\n@@@@@@@@@@@@@@@@@@@@@@@@");
    printf("\n%s\n",data.question);
    printf("\nA. %s\n",data.a);
    printf("\nB. %s\n",data.b);
    printf("\nC. %s\n",data.c);
    printf("\nD. %s\n",data.d);
    printf("\n@@@@@@@@@@@@@@@@@@@@@@@@\n");
    printf("Answer: ");
   
    scanf("%s",ans);
   if(strcmp(data.answer, ans) == 0)
   {
    printf("\nCorrect\n");
   }
   else
   printf("\nIncorrent\n");
    }
    }
 
    
    fclose(filee);
}


void addquestion()
{
int count;
int i;
struct quiz q1;
FILE *ptr_myfile;

ptr_myfile=fopen("quiz.dat","ab");
if (!ptr_myfile)
{
cout<<"Unable to open file!";
exit(0);
}
printf("How much question you want to add: ");
scanf("%d",&count);
for(i=0;i<count;i++)
{
printf("\nEnter Question: ");
fflush(stdin);
scanf("%[^\n]",q1.question);
printf("\nChoice A: ");
fflush(stdin);
scanf("%[^\n]",q1.a);
printf("\nChoice B: ");
fflush(stdin);
scanf("%[^\n]",q1.b);
printf("\nChoice C: ");
fflush(stdin);
scanf("%[^\n]",q1.c);
printf("\nChoice D: ");
fflush(stdin);
scanf("%[^\n]",q1.d);
printf("\nEnter Answer: ");
fflush(stdin);
scanf("%s",q1.answer);
printf("\n\n");
fwrite(&q1, sizeof(struct quiz), 1, ptr_myfile);
}
fclose(ptr_myfile);
}