C++ Files and Streams

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this C++ tutorial, let’s discuss the C++ Files and Streams, different modes of opening a file and the sample program for better understanding the concept.

Introduction of Files and Streams in C++

To save the data for later use, the data must be stored on secondary storage. So, to save the data, files must be created. Data should be stored and retrieved from files. The data may be read from the console into the program or it may be printed from the program on the console. The data may also be saved in the file or it may be read from the file.

File Handling in C++

C++ uses streams for storing the data into the file or reading the same from the file. The streams act as an interface between files and the program.
A stream is the flow of data and is of two segments,

Input Stream: For reading data from the file
Output Stream: For writing data into the file

Classes for file handling

To read or write data, there must be a link that connects a stream with the file. This link is created using one of the following classes,
ifstream: for reading
ofstream: to writing

istream and ostream

Both the classes are derived from ios/istream is dedicated to input. ostream is dedicated to output.
The functions supported by istream are

  • get()
  • getline()
  • read()

The functions supported by ostream are

  • put()
  • write()

fstream

This class is derived from iostream. iostream inherits from istream and ostream. So, fstream can handle both input and output.

Different modes of opening a file

ios::in  = read mode
ios::out = write mode
ios::ate  = takes the cursor to the end of file when the file is opened
ios::app = append mode. Starts writing at the end of file
ios::trunc = Remove the contents of the file. i.e. truncates the file
ios::binary = Opens the file in binary mode

C++ Program describing the usage of Files and Stream

The code discussed asks the user for the employee name and age. It writes the same in file.

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
char empname[30];
double salary;
char choice;
ofstream os("emp.txt");
do
{
cout<<"\nEnter empname:";
cin>>empname;
os<<empname<<"\n";
cout<<"\nEnter salary:";
cin>>salary;
os<<salary<<"\n";
cout<<"\nDo you want to enter more employees(Y/N):";
cin>>choice;
}while (choice=='Y' || choice=='y');
os.close();
cout<<"\nData stored in the file;
}

Output

Enter empname: anu
Enter salary: 40000
Do you want to enter more employees(Y/N): n
Data stored in the file

 

Leave a Comment

Your email address will not be published. Required fields are marked *