File I/O (Input/Output) in C refers to the process of reading from and writing to files on the disk. File I/O in C is done using the standard library functions provided in stdio.h. These functions allow you to open files, read from or write to them, and close them when done.
Types of File I/O operations
1. Opening a file
2. Reading from a file
3. Writing to a file
4. Closing a file
Open a File
To open a file in C, you use the fopen() function. It requires two arguments:
1. The name of the file.
2. The mode in which you want to open the file.
Syntax:
FILE *fopen(const char *filename, const char *mode);
Explanation:
- filename is the name of the file to be opened.
- mode specifies the file access mode (whether to read, write, append, etc.).
There are many modes of File
Mode
Description
r
Read mode: Open an existing file for reading
w
Write mode: Create an empty file for writing. If the file already exists, it’s truncated.
a
Append mode: Open an existing file for appending or create a new file if it doesn’t exist.
r+
Read and write mode: Open for both reading and writing. The file must exist.
w+
Write and read mode: Create an empty file for both writing and reading.
a+
Append and read mode: Open a file for reading and appending.
b
Binary mode: Add this character to modes to work with binary files (e.g., “rb”, “wb”, etc.).