C++/fstream

Advertisement


Question
Hello Ralph, thanks for your fast response last week.  
My question now is about fstream.  I was trying to do some binary file reading.  I wanted to declare two files, one for input and one for output.  In reality, I had several files to read and several to write, but to avoid clutter I hoped to only use two declarations.  
My problem is that when I tried to reuse my infile variable, the get pointer wouldnt' seek correctly.  I even did

...
ifstream inFile;
inFile.open("validfilename", io::in | io::binary);
...
infile.seekg(0; ios::beg);
i = infile.tellg();
...

and 'i' would return -1.  Are we not allowed to reuse ifstream variables more than once?
  Jed

Answer
Yes you can. But you have to close the previous file _before_ opening another otherwise the open will fail. Either that or your stream is in an erroneous state for some other reason. Some error checking on the stream state might be a good idea!

Also please if you post code could you actually copy and paste it from source code you have compiled? The few lines you show not only do not really show what you are doing (so I am guessing that you have not closed the previous file from the described behaviour), but also contain many errors!

Consider the following test program based on your code:

#include <iostream>
#include <fstream>

void PositionFile( std::ifstream & inFile )
{
   if ( inFile )
   {
       inFile.seekg(0, std::ios::beg);
       std::cout << "Position: " << inFile.tellg() << '\n';
       inFile.seekg(10, std::ios::beg);
       std::cout << "Position: " << inFile.tellg() << '\n';
   }
   else
   {
       std::cerr << "Bad Infile!\n";
   }
}


int main()
{
   std::ifstream inFile;
   inFile.open("test.txt", std::ios::in | std::ios::binary);
   PositionFile( inFile );

   inFile.close(); // ### close previous file before opening another!
   
   inFile.open("test.dat", std::ios::in | std::ios::binary);
   PositionFile( inFile );

}

Here I have shown how I am using the same std::ifstream to open one file after another. I also check in the PositionFile function that the passed in stream is in a good state (not in a failed or bad state). This is fairly crude as checking goes but does for this example. I have changed the filenames to ones I had available. The output is as follows:

Position: 0
Position: 10
Position: 0
Position: 10

If you comment out the inFile.close(); line then the second call to PositionFile has a stream in a bad state and it outputs:

Position: 0
Position: 10
Bad Infile!

To see the behaviour you observed remove the checking from PositionFile so that it reads:

void PositionFile( std::ifstream & inFile )
{
   inFile.seekg(0, std::ios::beg);
   std::cout << "Position: " << inFile.tellg() << '\n';
   inFile.seekg(10, std::ios::beg);
   std::cout << "Position: " << inFile.tellg() << '\n';
}

Which with the inFile.close(); line still commented out or removed should output:

Position: 0
Position: 10
Position: -1
Position: -1

This was the same for VC++ 2005 on Windows XP x64 and g++ 4.0.2 under SuSE Linux 10 (x64 edition). In fact returning -1 if tellg fails is standard behaviour.

Hope this helps.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.