C Library - fprintf() function



The C library fprintf() function is used to write formatted data to a stream. It is part of the standard I/O library <stdio.h> and allows you to write data to a file stream as opposed to printf() which writes to the standard output stream.

Syntax

Following is the C library syntax of the fprintf() function −

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

Parameters

This function accepts the following parameters −

  • stream :A pointer to the FILE object that identifies the stream where the output is to be written.
  • format : A string that specifies the format of the output. It may contain format specifiers that are replaced by the values specified in the subsequent arguments.
  • ... : Additional arguments that correspond to the format specifiers in the format string.

Return Value

The fprintf() function returns the number of characters written if successful, and a negative value if an error occurs.

Example 1: Writing to a File

This example opens a file named "output.txt" in write mode, writes "Hello, World!" to it using fprintf(), and then closes the file.

Below is the illustration of C library fprintf() function.

 #include <stdio.h> int main() { FILE *file_ptr; // Open file in write mode file_ptr = fopen("output.txt", "w"); if (file_ptr == NULL) { printf("Error opening file!"); return 1; } fprintf(file_ptr, "Hello, World!\n"); // Close the file fclose(file_ptr); return 0; } 

Output

The above code produces following result−

 Hello, World! 

Example 2: Writing Multiple Lines

This example shows how to write multiple lines to a file using successive calls to fprintf().

 #include <stdio.h> int main() { FILE *file_ptr; file_ptr = fopen("output.txt", "w"); if (file_ptr == NULL) { printf("Error opening file!"); return 1; } fprintf(file_ptr, "Line 1\n"); fprintf(file_ptr, "Line 2\n"); fprintf(file_ptr, "Line 3\n"); fclose(file_ptr); return 0; } 

Output

After execution of above code, we get the following result

 Line 1 Line 2 Line 3 
Advertisements