How to Read Files in C: A Comprehensive Guide to File Operations
Discover how to read files in C programming with our detailed guide. Building on the previous chapter about writing to files using w
and a
modes with the fopen()
function, this chapter focuses on using the r
mode. Learn to efficiently retrieve and manipulate data from files in your C programs.
Write to Files in C
Writing to a File
In this section, we will explore how to write content to a file using the w
mode. This mode allows you to open a file specifically for writing. To add text to the file, you can use the fprintf()
function, which takes the file pointer (like fptr
in our example) and the text you want to write.
Example
#include
int main() {
FILE *fptr;
// Open a file in writing mode
fptr = fopen("example.txt", "w");
// Write some text to the file
fprintf(fptr, "This is a sample text.");
// Close the file
fclose(fptr);
return 0;
}
Result
When you open the file on your computer, it will contain:
This is a sample text.
Important Note
If you write to a file that already exists, any previous content will be erased, and the new content will replace it. For instance, if you run the following code:
Example
fprintf(fptr, "Goodbye World!");
Result
After executing the above code, if you open the file, it will now display:
Goodbye World!
Appending Content to a File
If you want to add content to a file without losing the existing content, you can use the a
mode. This mode appends text at the end of the file.
Example
#include
int main() {
FILE *fptr;
// Open a file in append mode
fptr = fopen("example.txt", "a");
// Append some text to the file
fprintf(fptr, "\nWelcome to file handling in C!");
// Close the file
fclose(fptr);
return 0;
}
Result
When you open the file on your computer after appending, it will look like this:
This is a sample text.
Welcome to file handling in C!
Important Note
Just like with the w
mode, if the file does not exist, the a
mode will create a new file and add the "appended" content to it.