In our first program on disk I/O we have opened the file in read (“r”) mode. However, “r” is but one of the several modes in which we can open a file. Following is a list of all possible modes in which a file can be opened. The tasks performed by fopen( ) when a file is opened in each of these modes are also mentioned.
Mode | Explanation |
---|---|
"r"
|
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL. Operations possible – reading from the file. |
"w"
|
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.Operations possible – writing to the file. |
"a"
|
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.Operations possible – adding new contents at the end of file. |
"r+"
|
Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file. Operations possible – reading existing contents, writing new contents, modifying existing contents of the file. |
"w+"
|
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file. Operations possible – writing new contents, reading them back and modifying existing contents of the file. |
"a+"
|
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. Operations possible – reading existing contents, appending new contents to end of file. Cannot modify existing contents. |