"
This article is part of in the series

How To Use The C Library Function Fprintf()

C's fprintf() function shares similarities to the printf() function, in that they are both used to output text. 

The key difference between them is that fprintf() shares formatted output to a file stream rather than on the stdout console.

In this brief guide, we will help you understand what fprintf() is and how to use it.

What is the fprintf() Function?

Programmers sometimes find the need to write data into files rather than the terminal, and this is where the fprintf() function comes in. 

In C, the function is known as the format print function. You can find the function's definition in the stdio.h header file. 

The interesting thing about this function is that it can send a formatted output string to a stream. It counts the number of characters successfully written to the file and returns the count. If the function fails, it returns an EOF.

Syntax of the fprintf() Function 

Declaring the fprint() function in a C program is quite straightforward. You can use the syntax:

int fprintf (FILE * stream, const char * format, ...)

 

In C, when using the fprintf function, you provide a stream, which is a pointer to a file object where you want to write data and a format containing the text you want to write to the stream. 

If the operation is successful, fprintf() returns an integer indicating the number of characters written to the file.

Parameters Supported by fprintf()

The fprintf() function can accept two arguments: stream and format.

The stream argument is the pointer to a FILE object. It helps identify the sequence of file objects where data should be written. 

The C string represents the text from the file indicated by the stream pointer. 

You can include format tags, which will be substituted with the values provided in the subsequent arguments.

The blueprint of a format tag is as follows:

% [flags][width][.precision][length]specifier.

 

Let's understand the components of this tag one after another, beginning with the flags.

Flags

Flags Description
(space) If no sign is specified, a blank space comes before the value.
- The text is aligned to the left.
+ A plus (+) or minus (-) sign is added before the result.
0 Pads the number with zeroes rather than spaces.
# It is used with o, x, or X specifiers when all values except zero are preceded by 0, 0x, or 0X.

 

Width

Width Description
(number) This indicates the minimum number of characters to be written into the file. If the printed value is smaller than this number, spaces fill the gap between the two numbers.
* This denotes that the width isn't specified in the format string but is provided as an integer argument after the argument that needs formatting.

 

Precision

.precision Description
.number It sets the minimum number of digits needed for the printed number in the file for integer specifiers like i, d, u, o, x, or X. If the number is smaller than the specified minimum, leading zeros (0) are added. If the number exceeds the specified minimum, it won't be truncated. All characters are printed by default until a null character is found unless a specific value is provided.
.* It indicates that the precision isn't specified within the format string itself; instead, it's provided separately as an integer argument to the function.

 

Specifiers

Specifier Meaning
c C character
d or i Signed decimal integer
e (mantissa) Used for scientific notation using e character
E (mantissa) Used for scientific notation using the E character
f Decimal floating-point number
g shorter of %f or %e
G shorter of %f or %E
o signed octal
p Pointer address
s String of characters
u Unsigned decimal integer
x unsigned hexadecimal number
X unsigned hexadecimal number

 

Length

Length Description
l It's understood as either a long or an unsigned long integer for characters or character strings (c and s) and integer specifiers (d, i, o, u, x, and X).
h This argument for length can be understood as either an unsigned short integer or a short integer. It's only applicable to integer specifiers.
L This argument is seen as a long double and is only relevant for floating-point specifiers such as g, f, R, and e.

 

Depending on the format string passed to the fprintf() function, it may expect some additional arguments. Additionally, these extra arguments expect a value for every "%" tag present in the format string.

The Return Value of the fprintf() Function

This function returns an integer value representing the number of characters printed into a file.

If the function encounters some issue when writing to the file stream, it stops and returns a negative value. 

Example of fprintf() Function

Before you use the fprintf() function in C, you must open the text file in write mode in a specific position. Of course, you will need to use a file pointer. 

Next, you must write the string into the file by passing the pointer and the string to the fprintf() function. Here's an example:

#include <stdio.h>

int main() {

  char input[100];

  FILE *filePointer;

  int numberOfInputs, i;

  filePointer = fopen("output.txt", "w");

  if (filePointer == NULL) {

    printf("Error: Unable to open file!");

    return 0;

  }

  printf("Enter number of inputs to write to the file: ");

  scanf("%d", &numberOfInputs);

  for (i = 1; i <= numberOfInputs; i++) {

    printf("Enter input %d: ", i);

    scanf("%s", input);

    fprintf(filePointer, "Input %d: %s\n", i, input);

  }

  fclose(filePointer);

  return 0;

}

 

This program prompts the user for a certain number of inputs, writes those inputs to a file along with their indices, and then closes the file.

Let's assume a user gives this program the following inputs:

Enter number of inputs to write to the file: 3

Enter input 1: Apple

Enter input 2: Banana

Enter input 3: Orange

 

After the user enters these inputs, the program writes them into a file named "output.txt" in the following format:

Input 1: Apple

Input 2: Banana

Input 3: Orange

 

Another Example of fprintf() Function

The program below prompts the user for student information and then writes it to a file named "student_info.txt" before closing the file.

#include <stdio.h>

int main() {

  // Initializing file pointer.

  FILE *file_pointer;

  file_pointer = fopen("student_info.txt", "w");

  // If file_pointer is a null pointer, the file opening failed.

  if (file_pointer == NULL) {

    printf("Failed to open file!");

    return 0;

  }

  int roll_number;

  char name[50];

  float gpa;

  // Input student info from the user.

  printf("Enter student's name: ");

  scanf("%s", name);

  printf("Enter student's roll number: ");

  scanf("%d", &roll_number);

  printf("Enter student's GPA: ");

  scanf("%f", &gpa);

  // Writing data into the file.

  fprintf(file_pointer, "Name: %s\n", name);

  fprintf(file_pointer, "Roll Number: %d\n", roll_number);

  fprintf(file_pointer, "GPA: %.2f\n", gpa);

  // Close opened file.

  fclose(file_pointer);

  return 0;

}

 

Let's assume that the user gives the program these inputs:

Enter student's name: John Doe

Enter student's roll number: 12345

Enter student's GPA: 3.75

 

After the user enters this information, the program creates a file named "student_info.txt" and writes the following content into it:

Name: John Doe

Roll Number: 12345

GPA: 3.75

 

If the file creation or writing fails, the program will output "Failed to open file!" instead of creating the file and writing the information.