What is fprintf in C?

The fprintf function allows the programmer to redirect the standard output to a file instead of the console. Simply put, it lets the programmer write a string into a file.

Difference between printf and fprintf

Figure 1: Difference between printf and fprintf functions

As shown in the figure above, fprintf works exactly like printf, but for files. It prints the content of the character array into the file specified by the programmer.

Syntax

int fprintf(FILE *pointerToFile, const char *stringToPrint, ...);

In the above snippet of code, pointerToFile is the pointer of type FILE returned by the fopen function, and stringToPrint is the character array that is to be printed in the file.

Return Value

If the function executes successfully, it will return the number of characters written into the file.

In case of failure, a negative number is returned.

Example 1

The following piece of code prints a simple Hello, World! statement in the file output.txt:

#include<stdio.h>
int main() {
// sample string to write in the file
char sampleString[] = "Hello, World!";
char str[1000];
//opening the file for writing
FILE *filePointer = fopen("output.txt", "w+");
// checking if the file opened successfuly
if(filePointer != NULL){
// writing in the file
int response = fprintf(filePointer, sampleString);
// checking if fprintf executed successfully
if(response < 0){
printf("Unable to write in the specified file.");
}
}
// closing the file
fclose(filePointer);
// reading file to see if the write was successful
filePointer = fopen("output.txt", "r");
while (fgets(str, 1000, filePointer) != NULL){
printf("Text file: %s", str);
}
fclose(filePointer);
return 0;
}

Example 2

The following piece of code prints numbers 1 to 10 (in each line) in the specified file:

#include<stdio.h>
int main() {
//opening the file for writing
FILE *filePointer = fopen("output.txt", "w+");
char str[1000];
// checking if the file opened successfuly
if(filePointer != NULL){
// loop to print the numbers 1 to 10
for(int i = 1; i <= 10; i++){
fprintf(filePointer, "%d\n", i);
}
}
// closing the file
fclose(filePointer);
// reading file to see if the write was successful
filePointer = fopen("output.txt", "r");
while (fgets(str, 1000, filePointer) != NULL){
printf("Text file: %s", str);
}
fclose(filePointer);
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved