Writing To External Files
Lesson 29Author : Afrixi
Last Updated : January, 2023
In C, we can write data to external files using the fprintf()
function. This function takes a file pointer, which points to the external file we want to write to, as well as a formatted string and a list of variables to print to the file.
Here’s an example program that writes some text to an external file:
c Copy code #include <stdio.h>
int main() { // Open the file in write mode FILE *file = fopen(“output.txt”, “w”);
// Check if the file was successfully opened
if (file == NULL) {
printf("Error opening file.");
return 1;
}
// Write some text to the file
fprintf(file, "Hello, world!\n");
fprintf(file, "This is some text that will be written to the file.");
// Close the file
fclose(file);
return 0;
}
In this program, we first open the file "output.txt"
in write mode using the fopen()
function. We then check if the file was successfully opened by checking if the file pointer is NULL
. If it is, we print an error message and return an error code.
We then use the fprintf()
function to write some text to the file. We pass the file pointer
file, a formatted string, and some variables to print to the file. In this case, we print two strings to the file, separated by a newline character.
Finally, we close the file using the fclose()
function to ensure that any buffered data is written to the file and to release any resources associated with the file.