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.
SyntaxFollowing is the C library syntax of the fprintf() function −
int fprintf(FILE *stream, const char *format, ...);Parameters
This function accepts the following parameters −
The fprintf() function returns the number of characters written if successful, and a negative value if an error occurs.
Example 1: Writing to a FileThis 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4