File Handling In C

Reading or writing formatted IO using fscanf() and fprintf() functions.

The fprintf() function

So far we have seen writing of characters, strings and integers in different files. This is not enough if we need to write characters, strings and integers in one single file, for that purpose we use fprintf() function. The fprintf() function is used to write mixed type in the file.

Syntax
fprintf(FILE *fp,”format-string”,var-list);

The fprintf() function is similar to printf() function except the first argument which is a file pointer that specifies the file to be written.

example: fprintf()

This function helps us to write a set of data (combination of numeric and char fields like roll,name age etc) in the file.

fprintf(fp,”%d %s %f\n”,roll,name,age);
fp : is the file pointer used to open the file.

The fscanf() function

The fscanf() function is used to read mixed type form the file.
Syntax
fscanf(FILE *fp,”format-string”,var-list);

The fscanf() function is similar to scanf() function except the first argument which is a file pointer that specifies the file to be read.

Example :fscanf()

This function helps us to read a set of data (combination of numeric and char fields like roll,name age etc) from the file.

fscanf(fp,”%d %s %f”,&roll,name,&age);
fp : is the file pointer used to open the file. 

Reading or writing records using fread() and fwrite() functions.

The fwrite() function

The fwrite() function is used to write records (sequence of bytes) to the file. A record may be an array or a structure.
Syntax
fwrite( ptr, int size, int n, FILE *fp );

The fwrite() function takes four arguments.
ptr : ptr is the reference of an array or a structure stored in memory.
size : size is the total number of bytes to be written.
n : n is number of times a record will be written.
FILE* : FILE* is a file where the records will be written in binary mode.

The fread() function

The fread() function is used to read bytes form the file.
Syntax
fread( ptr, int size, int n, FILE *fp );

The fread() function takes four arguments.
ptr : ptr is the reference of an array or a structure where data will be stored after reading.
size : size is the total number of bytes to be read from file.
n : n is number of times a record will be read.
FILE* : FILE* is a file where the records will be read.

Number Of Visitors

0270451