Hi,
I am currently writing a code were the user is asked to enter details for the number of people they require. It's also required that the data must be saved, and then reloaded again to be displayed on the screen. However, when reloading the data, 'Oh dear' appears which is part of the if funtion, which should only appear if something is wrong with the file_load or file_save function. Here is the current code:
Code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#define name_length 20
struct Details
{
char surname[name_length];
char forename[name_length];
int birth_year;
int birth_month;
int birth_day;
};
struct Details get_details(int);
void print_details(struct Details);
int file_save(int, char [], struct Details *);
int file_load(char [], struct Details *);
int main (void)
{
unsigned i,s;
struct Details *p;
printf("How many sets of details?");
scanf("%u",&s);
if((p=(struct Details *)malloc(s * sizeof(struct Details)))==NULL)
{
printf("Cannot allocate %u bytes",s);
getch();
return 1;
}
for (i=0;i<s;i++)
{
p[i]=get_details(i);
}
printf("Class details:\n");
for (i=0;i<s;i++)
{
print_details(p[i]);
}
printf("\n\nHit a key");
getch();
if((file_save(s,"datafile.txt",p))==0);
{
printf("Oh dear!\n");
}
s=file_load("datafile.txt",p);
if((s)==0)
{
printf("Oh dear!\n");
}
for (i=0;i<s;i++)
{
print_details(p[i]);
}
printf("\n\nHit a key");
getch();
free(p);
return 0;
}
struct Details get_details(int i)
{
struct Details get_member;
printf("\nDetails for class member %d",i+1);
printf("\nEnter the forename of the class member:");
scanf("%s",get_member.forename);
printf("\nEnter the surname of the class member: ");
scanf("%s",get_member.surname);
printf("\nEnter the year of birth of the class member: ");
scanf("%d",&get_member.birth_year);
printf("\nEnter the month of the birth of the class member: ");
scanf("%d",&get_member.birth_month);
printf("\nEnter the say of birth of the class member: ");
scanf("%d",&get_member.birth_day);
return get_member;
}
void print_details(struct Details print_member)
{
printf("\n %s %s \t%2d-%2d-%4d",print_member.forename,print_member.surname,print_member.birth_day,print_member.birth_month,print_member.birth_year);
}
int file_save(int size,char filename[],struct Details *fileptr)
{
int i;
FILE *fptr;
if((fptr=fopen(filename,"wb"))==NULL)
{
printf("File cannot be opened\n");
exit(1);
return 0;
}
fwrite(fileptr,sizeof(struct Details),size,fptr);
fclose(fptr);
return 1;
}
int file_load(char filename[],struct Details *fileptr)
{
FILE *fptr;
int size;
realloc(fileptr,size);
if((fptr=fopen(filename,"rb"))==NULL)
{
printf("File cannot be opened\n");
exit(1);
return 0;
}
fread(fileptr,sizeof(struct Details),size,fptr);
fclose(fptr);
return 1;
}
I have highlighted the areas in which i think the problem lies. Can someone point me in the right direction please?
Thanks, Luke.