Summary: in this tutorial, you will learn how to use C FILE I/O functions that deal with files handling.
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
FILE *fopen(const char *file_name, const char *mode);
*file_namespecifies the name of the file that you want to open.
fopen()function returns a
NULLpointer if the file does not exist or write-protected.
|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 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
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:
FILE* fp; fp = fopen("c:\\test\\test.txt","r");
Closing a file
After processing the file, you must close it using the
int fclose(FILE *fp);
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.