C++ offers the following classes to execute output and input of characters to/from the file system:

  1. ofstream: Stream class to write on files
  2. ifstream: Class stream for reading from files
  3. fstream: Stream the class from/to files to both read and write.

When you transfer the name as an argument, the function Object() { [native code] } for both classes (ifstream and ofstream) will actually open the file. There is also an open command for both classes (a file.open)) (and a close command (a file.close)). You are not needed to use the close command since it will be called automatically when the program finishes, but it is beneficial if you need to close the file long before the program ends.

The elegance of the C++ file handling system relies on the simplicity of the actual functions used in the simple operations of input and output. Since C++ supports overloading operators, it is possible to use < < and > > as cout or cin in front of the class case. In reality, file streams can be used after opening, exactly the same as cout and cin.

Example Program:

The following specifies the syntax required for a C++ program to open, read from, and write to, files.

To open a file 

We need to remind the machine about the intent of opening the file. For eg, writing on a file, reading from a file, etc. These are the various modes we can open a file in.

  • Ios::app opens to append a text file. (appending means inserting text at the end of the text).
  • Ios::ate opens an output file and transfers the read/write control to the file’s end.
  • ios::in opens a readable text file.

To include fstream and iostream, direct the C++ preprocessor. # include <fstream.h> and # include <iostream.h>

Declare that input streams are of the ifstream type. 

  1. E.g. inData, ifstream;
  2. Be aware that inData is simply an identifier name chosen by the programmer in this case.

Declare the output streams of the stream type.        

  1. For example, Ofstream OutData; Know that in this case, outData is simply an identifier name chosen by the programmer.

To connect file stream identifiers with disc files, use the open function.

  1.      E.g. inData.open(“input.txt file);;
  2.      E.g. OutData.open(“output file.txt);

Check the file identifier value to make sure there’s no problem with reading or writing to the disc. 


if (!inData)


cout << “** Problem: cannot open file_input.txt, ending program.”

<< endl;

return 1;


File identifiers are put together to the left of the insertion or extraction operator. This procedure occurs when reading or writing of file streams

  1. e.g.1 inData >> inVar1 >> inVar2;
  2. e.g.2 outData << inVar1;

Leave a Reply

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