C++ Change the Behaviour of Streams

We already have talked about various file modes. But now let's talk about their role in controlling a stream's behaviour.

When you open a file (i.e., link it with the stream) using constructor, the stream is activated in its default mode. The default mode for input type stream (ifstream type) is ios::in and for output type stream (ofstream type), it is ios::out.

The default behaviour of ifstream type stream (upon opening file) allows users to read contents from the file. If the filemode is ios::in only (e.g., fin.open("abc.dat", ios::in)) then reading is performed on a text file and if the filemode is ios::in | ios::binary (e.g., fin.open("abc.dat", ios::in | ios::binary)) then reading is performed on a binary file.

Changing the Default Behaviour of ofstream Type Stream

The default behaviour of an ofstream type stream (ios::out file mode), upon opening a file, is that it create the file if the file doesn't yet exist and it truncates the file (i.e., deletes its previous contents) if the file already exists. If you want to change this default behaviour, then you can do it by specifying any of the following file modes with open() function :

Modes Description
ios :: app to retain the previous contents of the file and to append to the end of existing file contents,
rather than truncating them.
ios :: ate to place file-pointer at the end of the file, but you can write data anywhere in the file.
ios :: trunc it causes the existing file to be truncated.
ios :: nocreate if file doest not exist, this filemode ensures that no file is created and hence open() fails.
However, if the file exists, it gets opened.
ios :: noreplace if the file does not exist, a new file gets created but if the file already exists,
the open() fails.


Here is an example program:

/* C++ Changing the Behaviour of Streams */

void main()
   char fname[20], ch;
   char ans='y';
   int rollno;
   float marks;
   ofstream fout;

   cout<<"Enter file name: ";
   cin.get(fname, 20);

   fout.open(fname, ios::app);
   while(ans=='y' || ans=='Y')
      cout<<"\nEnter rollno: ";
      cout<<"Enter marks: ";
      cout<<"\nWant to enter more ? (y/n)..";

   cout<<"\nPress any key to exit...\n";

Here is the sample run of the above C++ program:

c++ change stream behaviour

More Examples

Here are some more examples listed, that you can go for:

C++ Online Test

« Previous Tutorial Next Tutorial »