Site icon i2tutorials

Reading and Writing Files

Reading and Writing Files

 

Writing to Files: fprintf( )

 

It is a predefined file handling function that is used to print the content in a file. The fprintf( ) function is identical to printf( ) function except that they work on files. The first argument of this function is a file pointer that specifies the file to be used. The general form of fprintf is:

 

Syntax:

 

fprintf(fp,”control string”, var_list);

 

Where fp id is a file pointer associated with an open file to write. The control string is a list of file output specifications that can include variable, constant, and string.

 

Example:

 

fprintf(fp, “%s%d%f”,name,age,weight);

 

In this case, the name is an array variable of type char and age is an int variable.

 

Reading from Files: fscanf( )

 

It is a predefined file handling function that is used to read the content from a file. The fscanf( ) function is identical to scanf( ) function except that they work on files. The first argument of this function is a file pointer that specifies the file to be used. The general format of fscanf is:

 

Syntax:

 

fscanf(fp, “controlstring”,var_list);

 

This statement would cause items to be read from the control string.

 

Example:

 

fscanf(fp, “%s%d”,name,&quantity”);

 

Where fp id is a file pointer combined with an open file for writing.The control string is a list of file output specifications that can include variable, constant, and string.

 

Exit mobile version