Writing to a file in C involves several steps:
Include necessary header files: To work with files in C, you need to include the
stdio.h
header file, which provides functions likefopen
,fwrite
, andfclose
for file operations.Declare a FILE pointer: You need to declare a pointer to a
FILE
structure, which will be used to represent the file you want to work with.Open the file: You need to use the
fopen
function to open a file. This function takes two arguments: the name of the file you want to open and the mode in which you want to open it. For writing, you should use the "w" mode, which creates a new file or overwrites an existing file. If the file doesn't exist, it will be created; if it does exist, its contents will be truncated.Write to the file: You can use functions like
fprintf
orfputs
to write data to the file. In this case, we will usefprintf
to write a sentence to the file.Close the file: After you're done with writing, you should close the file using the
fclose
function. This step is important to ensure that any pending writes are flushed to the file and to release system resources associated with the file.
Here's a C program that writes a sentence to a file and then reads and displays the content of the file:
#include <stdio.h>
int main() {
// Declare a FILE pointer
FILE *file;
// Open the file for writing
file = fopen("output.txt", "w");
// Check if the file was opened successfully
if (file == NULL) {
printf("Failed to open the file.\n");
return 1; // Exit the program with an error code
}
// Write a sentence to the file using fprintf
fprintf(file, "This is a sentence written to a file.");
// Close the file
fclose(file);
// Reopen the file for reading
file = fopen("output.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("Failed to open the file for reading.\n");
return 1;
}
// Read and display the content of the file
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
// Close the file again
fclose(file);
return 0; // Exit the program with a success code
}
Explanation:
- The program opens a file called "output.txt" in write mode and writes the sentence "This is a sentence written to a file." to it.
- Then, it closes the file to ensure that the data is flushed to the file.
- It reopens the same file in read mode and reads and displays its content character by character until the end of the file (EOF) is reached.
- Finally, it closes the file again.
Output:
This is a sentence written to a file.
This program creates and writes to the "output.txt" file and then reads and displays the content from the same file.