The fopen() function is used for opening a file for reading, writing, and doing other operations. Here is its syntax:
FILE *fopen (const char *file_name, const char *mode)
Here, file_name represents the file that we want to work on and mode states the purpose for which we want to open the file. It can be any of the following:
- r: This opens the file in read mode and sets the file pointer at the first character of the file.
- w: This opens the file in write mode. If the file exists, it will be overwritten.
- a: Opens the file in append mode. Newly entered data will be added at the end of the file.
- r+: This opens the file in read and write mode. The file pointer is set to point at the beginning of the file. The file content will not be deleted if it already exists. It will not create a file if it does not already exist.
- w+: This also opens the file in read and write mode. The file pointer is set to point at the beginning of the file. The file content will be deleted if it already exists, but the file will be created if it does not already exist.
- a+: This opens a file for reading as well as for appending new content.
The fopen function returns a file descriptor that points to the file for performing different operations.