C++ Files and Streams

C++ Files and Streams: In the C++ files and streams the operations are performed by using streams too. By using the file handling we can store our data in the secondary storage device. The operations on files can be done by using three classes. They are as follows:

  • ofstream: Stream class to write on files
  • istream: Stream class to read from files
  • fstream: Stream class to both read and write from/to files.

file handling in C++

C++ Files and Streams

fstream

You have to include the fstream library to able to work with files. Class fstream encapsulates both properties of ifstream and ofstream classes. In this case, you want to open the file only for input operations, you have to use an ifstream object. In the case, you want only to write to file, use an ofstream object.

Achieving File Handling

For achieving file handling in C++, we should follow these steps

  • name a file
  • open the file
  • Reading data from a file
  • Writing data into a file
  • Closing a file

Functions used in the File Handling

Function Operation
open( ) To create a file
close( ) To close an existing file
get( ) Read a single character from a file
put( ) write a single character in a file
read( ) Read data from the file
write( ) Write data into a file

 File Opening Modes

There are different modes in which you can open a file:

  • in – file is opened for input.
  • out – file is opened for output.
  • binary – binary file is opened.
  • ate – output position is set to the end of the file when a file is opened.
  • app – all the outputs are appended to the existing contents of the file.
  • trunc – erase data from the file.

Example:

Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);

Open File by using open method
Calling of default constructor
ifstream fin;

fin.open(filename, openmode)
fin.open(“filename”);

fstream

The default value for fstream mode parameter is in | out. It means that the file is opened for reading and writing when you use fstream class.

Example:

fstream file;

//open file text.txt for input and output
file.open("test.txt");

//check if file is opened
if (!file.is_open())
  cout << " Cannot open file!" << endl;

//write a message to file
file << "This is the first line " << endl << "This is the second line" << endl;
file.seekg(ios::beg);//reset position of the input

//read first 5 number from test.txt
for (int i = 0; i != 5; ++i)
{
  //show read value on screeen
  cout << (char)file.get() << endl;
}

//get the next character from file
char next = file.get();
cout << "The next character is " << (char)next << endl;

//reset position again
file.seekg(ios::beg);
char* str = new char[50];

//extract first line into str
file.getline(str, 50);

//show first line
cout << str << endl;

//ignor next extracted character
file.ignore();

//show the next character without extracting it from file
cout << "Peek " << (char) file.peek() << endl;

//get current position
cout << "Current position is " << file.tellg() << endl;

//after all work with file is done
//close it
file.close();

Output:

T
h
i
s

istream

The istream allows object assignment. The predefined object cin is an object of this class and thus may be reassigned at run time to a different istream object.

Example:

#include <iostream> 
using namespace std; 
class demo { 
public: 
    int dx, dy; 
  
    // operator overloading using friend function 
    friend void operator>>(demo& d, istream& mycin) 
    { 
        // cin assigned to another object mycin 
        mycin >> d.dx >> d.dy; 
    } 
}; 
  
int main() 
{ 
    demo d; 
    cout << "Enter two numbers dx and dy\n"; 
  
    // calls operator >> function and 
    // pass d and cin as reference 
    d >> cin; // can also be written as operator >> (d, cin) ; 
  
    cout << "dx = " << d.dx << "\tdy = " << d.dy; 
}

Output:

Enter two numbers dx and dy
3 8
dx = 3 dy = 8

ofstream

When you use ofstream class, the default value for mode is out and the default value for an ifstream class is in.

Modes

Member Constant Represents Access
in * input File open for reading: the internal stream buffer supports input operations.
out output File open for writing: the internal stream buffer supports output operations.
binary binary Operations are performed in binary mode rather than text.
ate at end The output position starts at the end of the file.
app append All output operations happen at the end of the file, appending to its existing contents.
trunc truncate Any contents that existed in the file before it is open are discarded.

Close

File are closed by using close( ) member function.

Example:

void close();
//after all work with file is done
//close it
file.close();

get

You can extract characters from the stream when you open it for reading by using get( ) member functions. There are two possibilities to get unformatted input by using get( ) function.

Extract single character
 Syntax: char get();
Single character code is returned.

Extract C-string
Syntax: istream& get (char* str, int n, char delim = ‘\n’);
Extract characters into str until n-1 characters are not extracted or delim character is not met.

Example:

fstream file;
//open file text.txt for input and output
file.open("test.txt");
if (!file.is_open())
  cout << " Cannot open file!" << endl;
//write ten numbers to test.txt
for (int i = 0; i != 10; ++i)
  file << i << endl;//write i with newline character to text.txt
file.seekg(ios::beg);//reset position of the input
//read first 5 number from test.txt
for (int i = 0; i != 5; ++i)
{
  //show read value on screeen
  cout << (char)file.get() << endl;
}

Output:

0
1
2

getline

getline( ) member function extracts a line into an array of characters pointed by str until n-1 characters are not extracted or delim character is not met.

Syntax: istream& getline (char* str, streamsize n, char delim = ‘\n’);

ignore

ignore member function extracts characters from the file and ignores them until n characters are not extracted, delim or end of file (EOF).

Example:

istream& ignore (int n = 1, int delim = EOF);

If EOF is reached, the eofbit flag is set.

Peek

It returns the next characters in the stream but does not extract it.

Syntax: int peek( );

Putback

Putback function returns character c to stream.

Example:putback (char c);

seekg

There is a possibility to set the position of the next extracted value from the stream. It is done by using seekg functions.

Example: seekg (int pos);

tellg

In the same time, you can get the current position in the file input stream with tellg function.

Example: int tellg( );