File mode constants
Sno | Mode | Details |
1. | ios::in | to open the file in input mode. Whenever we want to read the file , we open the file in input mode i.e. in read mode. The file should be present otherwise error gets generated. |
2 | ios::out | to open the file in output mode. Whenever we want to create a file , we open the file in output mode. File gets created , if the file of the specified name is already present it will be overwritten. |
3 | ios::app | to open the file in append mode i.e. To add data into an existing file. |
4 | ios::ate | open the file and take the file pointer to the end of the file. By default whenever the file is opened the file pointer is placed at the starting of the file. |
5 | ios::trunc | The contents of the existing file are deleted i.e. the file is deleted and recreated. |
6 | ios::nocreate | This causes the open() function to fail if the file does not exist. It will not create a new file with the specified name. |
7 | ios::noreplace | The open function fails if the file is already present. |
8 | ios::binary | This helps us to open the file in binary mode. By default the file is opened in text mode. |
If required we can combine two or more file modes.
Example:
fstream abc;
abc.open(“hello”,ios::app | ios::nocreate);
Will open the file in append mode if the file is present, and will abandon the file opening operation if the file does not exist.
To open the file in binary mode we have to specify the ios::binary along with the file modes.
abc.open(“hello”,ios::app | ios::binary);
abc.open(“hello”,ios::out | ios::nocreate | ios::binary);
Closing the file
Member function “close()” helps us to close the file. Member function close is invoked using the object using which the file is opened.
example:
ifstream abc;
abc.open(“filename”);
where
fstream : is an inbuilt class
abc: user defined object to open the file in input mode i.e. reading.
filename: user defined filename to store the data
To close the above file:
Example:
abc.close();
where:
abc: user defined object to open the file in input mode i.e. reading.
close(): inbuilt function used to close the file.
Example:
ifstream abc;
abc.open(“hello.txt”);
statements
statements
abc.close();