Here is a program in C that illustrates the use of fprintf() to write a text file:
Program in C illustrating the use of fprintf() to write a text file:
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("output.txt", "w");
if(fptr == NULL) {
printf("Error!");
return 1;
}
fprintf(fptr, "This is a text file created using fprintf!");
fclose(fptr);
return 0;
}
Explanation for each step:
- Include the necessary header file:
#include <stdio.h>
: This line includes the standard input/output header file, which contains the definition for thefprintf()
function.Define the main function:
int main() { ... }
: This is the entry point of the program, where the execution begins.Declare a file pointer:
FILE *fptr;
: This line declares a file pointerfptr
which will be used to handle the file operations.Open the file in write mode:
fptr = fopen("output.txt", "w");
: This line opens a file named "output.txt" in write mode. If the file doesn't exist, it will be created. If it does exist, its contents will be truncated.Check for file opening errors:
if(fptr == NULL) { ... }
: This condition checks if the file opening was successful. If the file pointer isNULL
, an error message is printed, and the program returns with an error code.Write to the file using fprintf():
fprintf(fptr, "This is a text file created using fprintf!");
: This line uses thefprintf()
function to write the specified text to the file pointed to byfptr
.Close the file:
fclose(fptr);
: This line closes the file associated with the file pointerfptr
after the writing operation is complete.Return from main function:
return 0;
: This line indicates a successful execution of the program, and the main function returns 0 to the operating system.