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.
1 | FILE* fp; |
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:
1 | FILE *fopen(const char *file_name, const char *mode); |
In the fopen()
function:
- The
*file_name
specifies the name of the file that you want to open.
- The
mode
- The
fopen()
function returns aNULL
pointer if the file does not exist or write-protected.
Mode | Meaning |
---|---|
r | Open file for reading |
w | Open file for writing. If the file exists, fopen function deletes content and overwrites it otherwise a new file is created. |
a | Open 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, e
tc. For example, to open a text file named test.txt
in the folder c:\temp
you use the fopen()
function as follows:
1 2 | FILE* fp; fp = fopen("c:\\test\\test.txt","r"); |
Closing a file
After processing the file, you must close it using the fclose()
function:
1 | int fclose(FILE *fp); |
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:
1 | flcose(fp); |
In this tutorial, we’ve introduced some standard I/O function that deals with opening and closing files in C.