File I/O (input/output) operations in C refer to the ability to read data from and write data to files on a disk or other storage device. File I/O is essential for many types of programs, including those that handle large amounts of data, such as databases and media players.
In C, file I/O operations are performed using the standard I/O library, which provides a set of functions for opening, reading from, writing to, and closing files. The basic steps for performing file I/O in C are as follows:
Open the file using the fopen() function. This function takes two arguments: the name of the file and the mode in which to open it.
Perform the desired read or write operation using functions such as fread(), fwrite(), fscanf(), or fprintf(), depending on the data type and format.
Close the file using the fclose() function when the operations are complete.
The modes for opening a file in C are:
"r": open for reading (file must exist)
"w": open for writing (truncate file to zero length or create new file)
"a": open for appending (write to end of file or create new file)
"r+": open for reading and writing (file must exist)
"w+": open for reading and writing (truncate file to zero length or create new file)
"a+": open for reading and appending (write to end of file or create new file)
Here is an example of opening a file for writing and writing data to it:
#include <stdio.h>
int main() {
FILE *fp;
char str[] = "This is a test string.";
fp = fopen("testfile.txt", "w");
if (fp == NULL) {
printf("Error opening file.");
return 1;
}
fwrite(str, sizeof(char), sizeof(str), fp);
fclose(fp);
return 0;
}
In this example, the fopen() function is used to open a file named "testfile.txt" in write mode. The fwrite() function is then used to write a test string to the file, and the fclose() function is used to close the file.
It is important to note that file I/O operations can fail due to various reasons, such as the file not existing, insufficient permissions, or disk errors. It is therefore important to check the return value of file I/O functions and handle errors appropriately.