Don't let the garbage deter you - this is the right way to go, and quite a thing of elegance when you see it working right.
I know it's frustrating - but hang in there. You're close. I'm putting your code into good old Turbo C and looking at it, just now.
Back in a bit.
Code:
#include<stdio.h>
main()
{
FILE *fp;
char another;
int i;
struct customer
{
int accno;
char name[40];
float balance;
};
struct customer c;
another = 'Y';
fp = fopen("customer.dat","wb");
if(fp == NULL)
{
printf("Cannot open file");
fclose(fp);
exit(1);
}
while(another == 'Y')
{
printf("Enter customer details\n");
scanf("%d %s %f",&c.accno,c.name,&c.balance);
fwrite(&c,sizeof(c),1,fp);
printf("Add another?\n");
//fflush(stdin); this has been deprecated, for
//input streams. (use for output streams only)
//replace with:
i=getchar();
scanf("%c",&another);
i=getchar(); //removes the newline left by scanf();
}
fclose(fp);
//end of writing data, start of reading data
fp = fopen("customer.dat","rb");
if(fp == NULL)
{
printf("Cannot open file for reading");
fclose(fp);
exit(1);
}
another = 'Y';
while(another == 'Y')
{
printf("Enter customer detials\n");
//scanf("%d %s %f",&c.accno,c.name,&c.balance);
fread(&c,sizeof(c),1, fp);
//fwrite(&c,sizeof(c),1,stdout); //shows the "gobbledy-gook".
printf("\n\n");
printf("\n Number: %d", c.accno);
printf("\n Name: %s", c.name);
printf("\n Balance: %.2f\n", c.balance);
printf("Read another record?\n");
scanf("%c",&another);
i=getchar(); //removes the newline left by scanf();
}
fclose(fp);
printf("\n\n\t\t\t press enter when ready");
i=getchar(); ++i;
return 0;
}
Made some changes to accommodate TC. Now shows the file contents in readable form.