File Modes - Unit 5
File Modes - Unit 5
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
ofstream: This Stream class signifies the output file stream and is applied
to create files for writing information to files
ifstream: This Stream class signifies the input file stream and is applied
for reading information from files
fstream: This Stream class can be used for both read and write from/to
files.
1 open() function
Syntax
#include <fstream>
std::fstream file;
file.open("filename.txt", mode);
The second argument represents the mode in which the file has to be opened.
The following modes are used as per the requirements.
Modes Description
in Opens the file to read(default for ifstream)
out Opens the file to write(default for ofstream)
binary Opens the file in binary mode
app Opens the file and appends all the outputs at the end
ate Opens the file and moves the control to the end of the file
trunc Removes the data in the existing file
nocreate
Do not Does not allow to create new file if it does not
create exist.
Do not replace Does not replace old file with new file.
noreplace
Example
1 fstream new_file;
2 new_file.open(“newfile.txt”, ios::out);
ifstream - ios::in
ofstream- ios::out
fstream - ios::in | ios::out
Example
ofstream new_file;
As soon as the program terminates, the memory is erased and frees up the
memory allocated and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use
of the file.
Using a stream insertion operator << we can write information to a file and
using stream extraction operator >> we can easily read information from a file.
Opening a file in ios::app mode (append mode):
This will append new content to the end of the file without overwriting existing
data.
#include <iostream>
#include <fstream>
using namespace std; // Allows using standard library names without the std::
prefix
int main()
if (outfile.is_open()) {
outfile.close();
} else {
return 0;
OUTPUT
Hello, World!
Appended Text.