fprintf() Function in C

Formatted File Input and Output

Up to this point, we have seen how to read and write characters and string to and from the file. In the real world, the data consists of many different types. In this chapter, we will learn how we can input and output data of different types in a formatted way. We use formatted input and output when we want to read or write data in a particular format.

fprintf() function

Syntax: int fprintf(FILE *fp, const char *format [, argument, ...] );

The fprintf() function is same as printf() but instead of writing data to the console, it writes formatted data into the file. Almost all the arguments of fprintf() function is same as printf() function except it has an additional argument which is a file pointer to the file where the formatted output will be written. On success, it returns the total number of characters written to the file. On error, it returns EOF.

The following program demonstrates how to use fprintf() function.

Expected Output:

How it works

In line 6, a structure pointer variable fp is declared of type struct FILE.

In line 7, an array of characters name of size 50 is declared.

In line 8, four variables namely roll_no, chars, i and n of type int are declared.

In line 9, a variable marks of type float is declared.

In line 11, fopen() function is called with two arguments namely “records.txt” and “w”. On success, it returns a pointer to file records.txt and opens the file records.txt in write-only mode. On failure, it returns NULL.

In line 13-17, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In line 19, a printf() statement prints “Testing fprintf() function: \n\n” to the console.

In line 21-22, the program asks the user to enter the number of students whose records he wants to enter.

In lines 24-41, a for loop asks the user to enter three pieces of information name, roll_no and marks of the respective students. In line 26, we are flushing (removing) the contents of the standard input, this line is necessary otherwise gets() function in line 30 will read the newline character (entered while asking the number of students) and will not wait for the user to enter the name of the student.

In line 38, fprintf() function is called along with 5 arguments to write formatted data to the file. If the data has been written successfully to the file, it returns the number of characters written to the file, which is then assigned to variable chars. In line 40, a printf() statement prints the total number of characters written to the file by the previous call of fprintf() function. The loop will keep asking for more records of students until i < n. As soon as n becomes greater than i, the control comes out of the for loop.

In line 43, fclose() function closes the file.

Leave a Comment