fprintf() function in C is another important function in file handling in c programming which is used to write a collection of data into the file.

What is fprintf() function in C?

As we know different file handling functions to write a single character, string or integer type of data to file. But one file can contain a different type of data which includes a combination of characters, string or integer so to write a mixed type of data to file fprintf is used.
fprintf() function in C:- This function is used to write a mixed (different)type of data to the File.

fprintf() function in C
fprintf() function in C

fprintf() Syntax in c
fprintf(FILE *fp,”format _seocifier”, variable list);

In the above syntax, we can see fprintf() function in C has 3 parameters which are as follows
FILE *fp :- The first parameter is file pointer which is a pointer to file which holds the address of the file.
Format specifier:- second parameter is format specifier which contains different format specifier for a different type (example:- for integer %d, for float %f )
Variable list:- This is a list of variable which we want to write to file.
The syntax for fprintf is the same as printf except fprintf accept first parameter file pointer which points to file.

fprintf function is the same as printf function, fprintf function writes data to file whereas printf writes data to the standard output screen.
fscanf function is used to read a mixed type of data from the file.

Why fprintf() function?

File is a collection of different types of data. Suppose if we want to write a combination of data (character and integer) then there are two ways to do this:

1. Use fputc() function to write character and after that use putw() to write integer to file.
2. Use the fprintf() function to write both characters and integers to file.
Obviously the second option is a better one to write data to file.

Program to demonstrate fprintf function

#include<studio.h>

void main()

{

FILE *fp;

int no;

char name[10];

printf ("\nopening file in write mode");

fp=fopen("technical.txt","w");. //Opening file in write mode

//Take input from user

printf("\nEnter no = ");

scanf("%d",&no);

printf ("\n Enter name = ");

gets(name);

//Writing no and name to file

fprintf (fp,"%d.%s",no,name);

printf ("\nwritten data using fprintf is successfully");

fclose(fp);

}

Program description: –
In the above program, we write the integer and string data to file.

1. First, we open a file in write mode. fopen(“technical.txt”,”w”) opens the file in write mode.
2. Take input from the user which want to write to file i.e no and name.
3. Next write fprintf(fp,”%d.%s”, no, name) which writes the integer type no and string name to the file.
4. Now you can see data stored to file.

Output: –

fprintf() function in C

Write A Comment