Working with fopen() and fclose()
Before you jump headfirst into working with files, you need to learn a bit about the fopen() function, which is used to open files. This function requires a filename and mode, and it returns a file pointer. A file pointer provides information about the file and is used as a reference.
Table for Modes Used with fopen()
- r Opens an existing file and reads data from it. The file pointer is placed at the beginning of the file.
- r+ Opens an existing file for reading or writing. The file pointer is placed at the beginning of the file.
- w Opens a file for writing. If a file with that name does not exist, the function creates a new file. If the file exists, the function deletes all existing content and places the file pointer at the beginning of the file.
- w+ Opens a file for reading and writing. If a file with that name does not exist, the function creates a new file. If the file exists, the function deletes all existing content and places the file pointer at the beginning of the file.
- a Opens a file for writing. If a file with that name does not exist, the function creates a new file. If the file exists, the function places the file pointer at the end of the file.
- a+ Opens a file for reading and writing. If a file with that name does not exist, the function attempts to create anew file. If the file exists, the function places the file pointer at the end of the file.