C File I/O

Summary: in this tutorial, you will learn how to use C FILE I/O functions that deal with files handling.

File Pointer

C provides a set of standard I/O functions that deal with file handling effectively. To access a file, first, you need a file pointer, which is a memory address of the file.

Opening a file

Before you can process a file, you need to open it. C provides the fopen() function that opens a file for reading, writing and appending. The following illustrates the fopen() function:

In the fopen() function:

  • The  *file_name specifies the name of the file that you want to open.
  • The mode parameter determines if the file is open for reading, writing or appending. See the table below for more detail.
  • The fopen() function returns a NULL pointer if the file does not exist or write-protected.
rOpen file for reading
wOpen file for writing. If the file exists, fopen function deletes content and overwrites it otherwise a new file is created.
aOpen file for appending. The fopen function creates the file if it does not exist.
r+Open file for reading and writing
w+Open file for reading and writing. The fopen function deletes content and overwrites the file if the file exists.
a+Open file for reading and writing. The fopen function appends file if it the file exists

The above modes are applied the text files. For the binary files, you just need to add b at the end of each mode such as rb, wb, ab, r+b, etc. For example, to open a text file named test.txt in the folder c:\temp you use the fopen()  function as follows:

Closing a file

After processing the file, you must close it using the fclose() function:

The fclose() function flushes the stream that is pointed by the file pointer *fp and close the file descriptor. The  fclose() function returns EOF or error code to indicate the error if there was an error occurred. If everything is fine, it returns 0. For example, to close the text file named test.txt that is pointed by the file pointer *fp, you use the fclose() function as follows:

In this tutorial, we’ve introduced some standard I/O function that deals with opening and closing files in C.

  • Was this tutorial helpful ?
  • YesNo