Output File Handling
Let’s talk about the output file handling. You can do several things with output files like, creation of a new file on the disk and writing data in it. Secondly, we may like to open an existing file and overwrite it in such a manner that all the old information is lost from it and new information is stored. Thirdly, we may want to open an existing file and append it in the end. Fourthly, an existing file can be opened and modified in a way that it can be written anywhere in the file. Therefore, when we open a file for output we have several options and we might use any one of these methods. All these things are related to the file-opening mode. The actual syntax of open function is:
open (filename, mode)
The first argument is the name of the file while the second will be the mode in which file is to be opened. Mode is basically an integer variable but its values are pre-defined. When we open a file for input, its mode is input file that is defined and available through the header files, we have included. So the correct syntax of file opening for input is:
myFile.open(“myfile.txt” , ios::in);
The 2nd argument ios::in associates myFile stream object with the “myfile.txt” for input. Similarly, for output files, there are different modes available. To open a file for output mode, ios::out is used. Here is the complete list of modes:
If a file is opened with ios::out mode, a new file is created. However, if the file already exists, its contents will be deleted and get empty unless you write something into it. If we want to append into the file, the mode will be ios::app. When we write into the file, it will be added in the end of the file. If we want to write anywhere in the file, the mode is ios::ate. We can position at some particular point and can write there. It is like append mode. But in ‘ate mode’ we can write anywhere in the file. With the trunc mode, the file is truncated, it is similar to out mode.
The file “myFileOut.txt”: