Opening and Closing a File


What is File ?

The file is a collection of data that can be in any format, and it may be text, image, or video. In C language, this data is represented in byte format.

File handling in C

In daily life, we need to handle data, some of it repeatedly, so the file is an excellent option to handle repeat data. There are various header files or libraries in the C language for file handling, allowing users to create, edit, open, delete or update any file. C language uses different functions to perform this operation on a file. We can perform the following operations on a file using the C language

  • Creating a file
  • Read a file
  • Write a file
  • Delete a file
  • Open an existing file

Opening a file

We can open an existing file using the fopen() function in the C language. While opening an existing file, we have to check that we open it before reading, writing, or updating the operation. Syntax of fopen() function is as follows,

FILE *fopen(const char *fname, const char *mode);

Here, fname is the file name which we want to open. The name can be like c://some_folder/some_file.txt. Also there are various mode in which we can open the file.

  • r : Open file in read mode.
  • w : Open file in write mode.
  • a : Open file in append mode.
  • r+ : Open file in read and write mode.
  • w+ : Open file in read and write mode.
  • a+ : Open file in read and write mode.

Closing a file

For closing a file, we use the fclose() function. This function must get executed after all the operations get performed.
The syntax is as follows,
int fclose(FILE *fp);