In C, the fprintf()
function is used to print formatted data to a file.
The general syntax of fprintf()
is:
int fprintf(FILE *stream, const char *format)
stream
: Pointer to the FILE object where data is to be printed
format
: This contains the data to be printed, written in a particular format using format specifiers
A format specifier is a unique character which is used to specify the data type of the value being read.
The format specifier follows the following prototype:
%[flags][width][.precision][length]specifier
If the function successfully executes, it returns the total number of characters written to the file. If an error occurs, a negative number is returned.
The following examples will help clarify the use of the fprintf()
function:
#include<stdio.h>int main() {FILE * stream;stream = fopen("/file.txt", "w");// Printing a stringchar str[20] = "Hello World!";int x = fprintf(stream, "%s", str);printf("\n %d characters successfully written to the file\n\n", x);// Printing an integer valueint age = 22;x = fprintf(stream, "%d", age);printf("\n %d characters successfully written to the file\n\n", x);fclose(stream);return 0;}
Free Resources