Certainly! Writing to files in C involves using the file handling functions provided by the standard I/O library. Here's a simple explanation with an example:
#include <stdio.h>
int main() {
FILE *filePointer; // Declare a file pointer
// Open file in write mode (creates the file if it doesn't exist)
filePointer = fopen("example.txt", "w");
// Check if file was successfully opened
if (filePointer == NULL) {
printf("Unable to open file.\n");
return 1; // Exit program with error
}
// Write content to the file
fprintf(filePointer, "This is line 1.\n");
fprintf(filePointer, "This is line 2.\n");
fprintf(filePointer, "This is line 3.\n");
// Close the file
fclose(filePointer);
printf("Content written to file successfully.\n");
return 0;
}
In this example
stdio.h
header file to use file handling functions.filePointer
.fopen()
function to open a file named "example.txt"
in write mode ("w"
). If the file doesn't exist, it will be created. The function returns a file pointer to the opened file.fopen()
returns NULL
, it means the file could not be opened, so we print an error message and exit the program.fprintf()
function to write content to the file. Here, we write three lines of text to the file.fclose()
function to free up system resources.When you run this program, it will create a file named "example.txt"
in the current directory (where the executable is located) and write the specified content to it. Each call to fprintf()
writes a new line to the file.