Saturday, 31 March 2012

Formatted Input/Output function


Formatted Input/Output function

To write / Read data in some specific format to a file , then need to use formatted input / output function like fprinf() and fscanf().

fprintf()

This function is used to write mixed data to a file.
Syntax:
                   fprintf(fp,”control string”,variable-list);
Here,
fp is the file pointer associated with a file that has been opened for writing purpose.The control string contains output specifications for the items in the list.The variable – list may include variables, constants and strings.

This function is similar to printf() except that a FILE pointer is include as a first argument which specifies the file to be used.


Ex,
FILE *fp;
fp = fopen(“data.txt”, “w”);
fprintf(fp,%d %s”,no,name);

As shown in above example fprintf() writes two different data to the file. where first is integer variable and second is character array.

fscanf()

This function is used to read mixed data from a file.
Syntax:
                   fscanf(fp,”control string”,variable-list);
Here,
fp is the file pointer associated with a file that has been opened for reading purpose.The control string is conversion character .The variable – list include address of variable which store the data.

This function is similar to scanf() except that a FILE pointer is include as a first argument which specifies the file to be used.
Ex,
FILE *fp;
fp = fopen(“data.txt”, “r”);
fscanf(fp,%d %s”,&no,name);

As shown in above example fscanf() reads two different data from file and store in variables, where first is integer variable and second is character array.

When the end of file is reached, it returns the value EOF.

Posted By : Ruchita Pandya

No comments:

Post a Comment