C – File Handling

What is file?

File is a collection of bytes that is stored on secondary storage devices like disk. There are two kinds of files in a system. They are,

  1. Text files (ASCII)
  2. Binary files

Basic file operations in C programming:

There are 4 basic operations that can be performed on any files in C programming language. They are,

  1. Opening/Creating a file
  2. Closing a file
  3. Reading a file
  4. Writing in a file

Let us see the syntax for each of the above operations in a table:

File operation

Declaration & Description

fopen() – To open a file

Declaration: FILE *fopen (const char *filename, const char *mode)

fopen() function is used to open a file to perform operations such as reading, writing etc. In a C program, we declare a file pointer and use fopen() as below. fopen() function creates a new file if the mentioned file name does not exist.

FILE *fp;
fp=
fopen (“filename”, ”‘mode”);

Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+. Please refer below the description for these mode of operations.

fclose() – To close a file

Declaration: int fclose(FILE *fp);

fclose() function closes the file that is being pointed by file pointer fp. In a C program, we close a file as below.
fclose (fp);

fgets() – To read a file

Declaration: char *fgets(char *string, int n, FILE *fp)

fgets function is used to read a file line by line. In a C program, we use fgets function as below.
fgets (buffer, size, fp);

where,
buffer – buffer to  put the data in.
size – size of the buffer
fp – file pointer

fprintf() – To write into a file

Declaration:
int
fprintf(FILE *fp, const char *format, …);fprintf() function writes string into a file pointed by fp. In a C program, we write string into a file as below.
fprintf (fp, “some data”); or
fprintf (fp, “text %d”, variable_name);

Mode of operations performed on a file in C language:

There are many modes in opening a file. Based on the mode of file, it can be opened for reading or writing or appending the texts. They are listed below.

1. Example program for file open, file write and file close in C language: