17 Jul C – File Handling
File Handling in C includes creating, reading, and writing a file. It also includes deleting a file. To work on files in C programming, we have the fopen() method which is a part of the <stdio.h> header file. To use it, declare a pointer of data type FILE.
Before that, let us first see the syntax of the fopen() method:
1 2 3 |
fopen(file_name, mode); |
Here, file_name is the name of the file you want to create.
The mode is the read mode, write, and append. Only a single character represents the mode:
- r – read a file
- w – write to a file
- a – append to a file
Create and close a File
To create a file in C programming, use the fopen() method and the mode w. Always remember to close an opened file using fclose() method.
Let’s say the name of the file we want to create is myfile.txt at the following location. Use the single backslash in Windows for the path as shown below:
1 2 3 |
E:\Amit\myfile.txt |
Let us now see an example to create a file in C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> int main() { FILE *fp; // Create a file myfile.txt fp = fopen("E:\Amit\myfile.txt", "w"); // Close the file using fclose() fclose(fp); return 0; } |
The file myfile.txt gets created at the location. The file is empty since we did not add any text to it:
Write to a File
To write to a File in C, use the fprintf() method, but before that open the file in w mode like we saw above. Set the pointer in the fprintf() and the text you want to write to the file myfile.txt.
Let us now see the C program to write text to the above file myfile.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <stdio.h> int main() { FILE *fp; // Open a file myfile.txt fp = fopen("E:\Amit\myfile.txt", "w"); // Writing text fprint(fp, "This is a demo text written to a file."); // Close the file using fclose() fclose(fp); return 0; } |
The myfile.txt file is now having the following text as shown below:
Read a File
To read a file in C Programming, use the fopen() method and the mode r. Always remember to close an opened file using fclose() method.
We will read the above myfile.txt with the following text:
Let us now see the example to read the above file i.e. myfile.txt that already exists:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <stdio.h> int main() { FILE *fp; // Open a file myfile.txt with mode r i.e., read fp = fopen("E:\Amit\myfile.txt", "r"); // Store the content of the file char str[50]; // Read the file // Using the while loop, we can read multiple lines in a file while(fgets(str, 50, fp)) { printf("%s", str); } // Display the file content printf("%s", str); return 0; } |
Output
1 2 3 |
This is a demo text written to a file. |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
No Comments