Following program will declare a Structure "customer". Program reads customer information and then writes into a "customer.dat" file.
#include <stdio.h>
//Define structure to store customer data.
struct customer
{
char fname[30];
char lname[30];
int ac_num;
float ac_balance;
};
void main ()
{
FILE *fp;
//declare structure(customer) variable
struct customer input;
// open customer file for writing
fp = fopen ("customer.dat","w");
if (fp == NULL){
printf("\nFile opening error..\n\n");
exit (1);
}
printf("Enter \"exit\" as First Name to stop reading user input.");
while (1)
{
printf("\nFirst Name: ");
scanf ("%s", input.fname);
if (strcmp(input.fname, "exit") == 0)
exit(1);
printf("Last Name : ");
scanf ("%s", input.lname);
printf("Account Number : ");
scanf ("%d", &input.ac_num);
printf("Balance : ");
scanf ("%f", &input.ac_balance);
// write customer data to customer.dat file
fwrite (&input, sizeof(struct customer), 1, fp);
}
}
Output of program
Enter "exit" as First Name to stop reading user input.
First Name: ABC
Last Name : PATEL
Account Number : 101
Balance : 55000
First Name: XYZ
Last Name : SHAH
Account Number : 102
Balance : 50000
First Name: exit
No comments:
Post a Comment