Hi everyone, i'm currently learning how to use C coding and been told to use the following: A menu, Structures, File handling and Dynamic memory allocation to collect data off x amount of people and i don't have a clue where to start to add dynamic memory allocation to the code. this is what i have so far.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include<string.h>
struct database
{
char fname[20],lname[20],email[35];
float tel_number;
};
struct database input;
char others='y';
void add()
{
FILE *datafile;
struct database input;
datafile = fopen ("data.dat","w");
if (datafile == NULL)
{
fprintf(stderr, "\nError opening data.dat\n\n");
exit (1);
}
printf("\n\nEnter \"quit\" as the first name to terminate program when all data added, then restart and choose option 2 to view stored records.\n");
while (1)
{
printf("\nFirst Name: ");
scanf ("%s", input.fname);
if (strcmp(input.fname, "quit") == 0)
exit(1);
printf("Last Name: ");
scanf ("%s", input.lname);
printf("Telephone Number: +44");
scanf ("%f", &input.tel_number);
printf("Email Address: ");
scanf ("%s", input.email);
fwrite (&input, sizeof(struct database), 1, datafile);
}
printf("Do you want to exit? y/n");
others=getche();
}
void read()
{
FILE *infile;
infile = fopen ("data.dat","r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening data\n\n");
exit (1);
}
while (fread (&input, sizeof(struct database), 1, infile))
printf ("\nName = %s %s Telephone = +44%.0f Email Address = %s,",input.fname, input.lname, input.tel_number, input.email);
getch();
}
int main()
{
char choice;
while(others=='y')
{
printf("Choose an option\n\n");
printf("1.Add Records \n");
printf("2.Show Records \n");
printf("Your Choice: ");
choice=getche();
switch(choice)
{
case '1':
add();
break;
case '2':
read();
break;
case '3':
exit(0);
}
printf("\nDo you want to continue? y/n");
others=getche();
}
getch();
return 0;
}