Home arrow C++ arrow Page 2 - File Handling and Streams in C++

File Handling and Streams in C++

Welcome to the fourth part of a ten-part series covering the use of streams with C++. Streams can save you a lot of time and effort that would otherwise be spent on trivial, tedious tasks. In this article, we'll show you how to use streams to improve the data flow of your applications.

Author Info:
By: Gabor Bernat
Rating: 4 stars4 stars4 stars4 stars4 stars / 7
April 07, 2009
  1. · File Handling and Streams in C++
  2. · Basic Tasks
  3. · The Mode Flags
  4. · The Binary Flag

print this article

File Handling and Streams in C++ - Basic Tasks
(Page 2 of 4 )

Inside the Iostream, you declare the three types of existing file streams: the input only stream is declared as "ifstream," the output only stream as "ofstream," and a combination of the two goes under the name of "fstream."

You have two different methods of opening/binding files to these streams. The first and the most convenient place to do so is in the constructor. Here you can simply pass the file name that also contains the extension type, and let the rest be resolved internally.

ofstream out ("In.txt");

Of course, this will be created in the default directory (that is where the application is running), but you can also give the path as a parameter to specify directly where to create the file. Alternatively, this tells the ifstream where to find the file and try to open it. Note that it has an additional constructor within as a second argument; you can pass on some open flags, but we will talk about this later.

The second way you can bind a file to the stream is by calling the open member function. This has the same capabilities as the constructor and will act just like it. You provide the input place, while the library will take care of all of the processes needed to open it for reading or writing into.

ofstream out;

out.open("In.txt"); // this will have the same effect as the //upper code

Here I should note that both types require having as an argument a "C style" string array, mainly for historical reasons. In any event, to get your path inside an STL-based string you can/need simply ask the string for a char* ( or wchar_t*) pointer using the "c_str()" member function as follows:

string name("C:In.txt"); // note that = for the string

ofstream out(name.c_str());

Sometimes the file cannot be created (not enough space) or just cannot be opened to be written to because it is read only. Checking to see if any errors occurred in the opening process can be done easily by checking to see if the stream is valid.



// here we react to the invalid file open


Whenever an error occurs during any process of a stream (including a file stream), a fail flag inside the class will be set to false. Until this is turned on, any task will be invalid, and most of the functions will just return an eof, just as if the stream has no more to offer. You can reset this by calling the clear function:

out.clear() // reset the error state of the stream

Generally, closing a stream is not required explicitly, because when the program finishes, during the destruction of the stream, the file will be automatically closed. It is advisable, however, to do this explicitly whenever you are not using the file. Let others use it or just avoid clumsy errors that could come if you decide later to perform other tasks on a different file and reuse this stream.

Yes, you read that right! You can re-use a declared stream once you close it and call the clear function in case any errors have popped up earlier. Let's assume we have a couple of file names inside a vector of strings and we want to read all of the data within a single string. Act as follows.

std::vector<string> files;

// fill up the vector

std::vector<string>::iterator it = files.begin();

std::vector<string>::iterator end = files.end();

ifstream in;

string temp;

while( it != end)


in.open (it->c_str());


while(in >> temp /* = in*/)

{// do whatever you want with the input





You can observe that after we read in a value from the stream, the while function will check not the input data, but the input stream. To comprehend this you should know that the line could be translated to a member function like this: in.operator<<(temp).

This function returns the stream itself to allow a chain construction of the insertion and extraction operators. Therefore, the "while" that will check the stream is reduced to checking to see if no error flag is turned on.

The way C++ tracks what have you written/read into a file is as follows: at the process of opening a file, besides associating with the stream one existing file on the HDD and opening that in an appropriate way, it will also create inside the stream object a file position indicator (FPI). This will help the stream in tracking where you are inside the file and what have you written/read recently.

Ignoring some input characters is possible by using the ignore() member function, which gets as an argument the number of characters to ignore. This is for those cases when you may have some invalid input and you want to just pass over it, not get the ugly error state every time. Moving through the file is possible with the seekg(), seekp(), tellg().

blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials