#include <stdio.h>
int main() {
// Declare a file pointer
FILE *filePtr;
// Open a file in write mode ("w")
filePtr = fopen("sample.txt", "w");
// Check if the file opened successfully
if (filePtr == NULL) {
printf("Error! Could not open file.\n");
return 1;
}
// Write data to the file
fprintf(filePtr, "Hello, File Handling in C!\n");
fprintf(filePtr, "This is an example of writing to a file.\n");
// Close the file
fclose(filePtr);
printf("Data written to the file successfully.\n");
return 0;
}
This program writes some text to a file named sample.txt
. If the file doesn’t exist, it will be created. If it exists, its contents will be overwritten.
Explanation:
FILE *filePtr
: This is the file pointer that points to the file.fopen("sample.txt", "w")
: Opens the file in write mode. If the file doesn’t exist, it is created.fprintf()
: Writes formatted text to the file, just likeprintf()
outputs to the console.fclose()
: Closes the file after the operation is done to release the resources.