Monday, March 28, 2011

Use of fprintf function in C file handling


The printf() function is used for formatted output on the standard output device. In a similar manner the fprintf() function is used for formatted output to files.
Syntax of fprintf() - fprintf(< file pointer >, "< format specifier >", < variable list >)

Program to create a data file using fprintf() function

#include < stdio.h >
void main()
{
FILE *ptr;
int a_no, i,records;
float balance;
char name[30];
clrscr();
printf("Program to create a data file to store information of a bank accounts using fprintf() \n\n");
ptr=fopen("dd.txt","a");
if(ptr == NULL) /* File opened in append mode */
{
printf("Cannot open the file for writing records ... terminating \n\n");
getch();
return;
}
printf("How many records do you want to add :");
scanf("%d", &records);
fflush(stdin);
for(i =0; i < records; i++) /* loop to enter data for number of records */
{
printf("Enter the account number :");
scanf("%d", &a_no);
fflush(stdin);
printf("\n Enter the name of the account holder :");
gets(name);
fflush(stdin);
printf("\n Enter the current balance :");
scanf("%f", &balance);
fflush(stdin);
/* Writing the record in the data file */
fprintf(ptr, "%4d, %30s, %f \n", a_no, name,balance);
} /* End of loop to input number of records */
fclose(ptr);
printf("Writing of records finished \n\n");
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner