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.
printf
and fprintf
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.
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.
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.
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 filechar sampleString[] = "Hello, World!";char str[1000];//opening the file for writingFILE *filePointer = fopen("output.txt", "w+");// checking if the file opened successfulyif(filePointer != NULL){// writing in the fileint response = fprintf(filePointer, sampleString);// checking if fprintf executed successfullyif(response < 0){printf("Unable to write in the specified file.");}}// closing the filefclose(filePointer);// reading file to see if the write was successfulfilePointer = fopen("output.txt", "r");while (fgets(str, 1000, filePointer) != NULL){printf("Text file: %s", str);}fclose(filePointer);return 0;}
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 writingFILE *filePointer = fopen("output.txt", "w+");char str[1000];// checking if the file opened successfulyif(filePointer != NULL){// loop to print the numbers 1 to 10for(int i = 1; i <= 10; i++){fprintf(filePointer, "%d\n", i);}}// closing the filefclose(filePointer);// reading file to see if the write was successfulfilePointer = fopen("output.txt", "r");while (fgets(str, 1000, filePointer) != NULL){printf("Text file: %s", str);}fclose(filePointer);return 0;}
Free Resources