C++ - SPLessons

C++ Stream

Chapter 35

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C++ Stream

C++ Stream

shape Description

Basically, iostream is one of the CPP Stream used for reading and writing into a program with the help of cin and cout.

Reading and writing into file can also be done using fstream standard library in files. fstream must be used as header file while doing input and output operations to a file along with iostream.

shape Table

CPP Stream Description
ofstream (taken from ostream) ofstream represents the output file stream and can be used to create files and to write data into files
ifstream (taken from istream) ifstream represents the input file stream and can be used to read data from files
fstream (taken from iostream) fstream represents both ofstream and ifstream and can be used to create files, writes data to files and read data from files.

File pointing using Streams

shape Description

File pointers are used to set the position of the data as per the requirement. The positioning can be done using few streams. They are

Some other functions used in fstream standard library are

//Declaring file using fstream
fstream eg_file;

//open file test.txt for read and write

//checking if file is opened
if (!eg_file.is_open())
cout << " Cannot open teh example file!" << endl;

//write information into file
eg_file << "Hello, welcome to splessons " << endl << "You are reading C++ tutorial" << endl;

//setting position of next extracted value

//read first 3 numbers from splessons.txt
for (int i = 0; i != 3; ++i)
	//diplaying the values which are read
	cout << (char)eg_file.get() << endl;

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

//reset position again
char* str = new char[50];

//copying first line into str
eg_file.getline(str, 50);

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

//ignore next extracted character

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

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

//closing the file


shape Key Points

CPP Stream chapter draws out following important points.

  • “fstream” is the header to do input/output operations in files.
  • File pointers sets the data position.