fprintf() and fscanf()
functions
Most
compilers support two functions namely fprintf() and fscanf() functions, that
can handle a group of mixed data simultaneously. The functions fprintf() and fscanf() perform
I/O operations that are identical to printf() and scanf() functions, except that
they work on files.
fscanf() funcnton: fscanf()
function is used to read mixed data simultaneously form a given file. The general format of the fscanf() function
is:
Syntax: fscanf(FilePointer,
“ControlString”, List);
Where,
FilePointer
associated with the file that has been opened for reading.
ControlString
consists of format specification for the items in the list.
List
may include variables, constants, strings etc.,
Function returns EOF marker whenever end of the
file has been reached.
fprintf() function: fprintf()
function is used to write mixed data simultaneously into a given file. The general format of the fpritnf() function
is:
Syntax: fprintf(FilePointer,
“ControlString”, List);
Where,
FilePointer
associated with the file that has been opened for writing.
ControlString
consists of output format specification for the items in the list.
List
may include variables, constants, strings etc.,
/* WRITE A PROGRAM TO CREATE A FILE THAT
CONTAINS INVENTORY DETAILS LIKE PRODUCT NUMBER, PRODUCT NAME AND PRODUCT
COST. READ THE SAME DATA FROM THE FILE
AND PRINT IT */
#include<stdio.h>
#include<conio.h>
struct product
{
int
id;
char
name[20];
float
price;
}p;
main()
{
char
flag='y';
FILE
*f;
clrscr();
f=fopen("product.dat","w");
while(flag=='y')
{
printf("\nEnter product id:");
scanf("%d",&p.id);
fflush(stdin);
printf("\nEnter product name:");
gets(p.name);
printf("\nEnter product cost:");
scanf("%f",&p.price);
fprintf(f,"%d\t%s\t%f\n",p.id,p.name,p.price);
printf("\nDo you want add another
record(y/n):");
fflush(stdin);
flag=getchar();
}
fclose(f);
f=fopen("product.dat","r");
if(f==NULL)
{
printf("\nFILE
OPENING ERROR");
exit();
}
printf("\nPRODUCT
DETAILS ARE:\n");
while((fscanf(f,"%d%s%f",&p.id,p.name,&p.price))!=EOF)
printf("\n%d\t%s\t%.2f",p.id,p.name,p.price);
fclose(f);
}
No comments:
Post a Comment