views:

129

answers:

2

I'm trying to create output files subscripted by a dynamic index ( d = {0,...,NUM_DEMES-1}). Currently, I'm only getting output files for the first value (d=0).

#include <sstream>
#include <string>

void Simulation::updateSimulation( double t )
{
 ...
 ofstream abundanceStream;
 ofstream abHeaderStream;     

 if ( step == 1 ) {
   for ( int d = 0; d < NUM_DEMES; d++ ) {
    abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::out);
    abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::out);
   }
 }

 for ( int d = 0; d < NUM_DEMES; d++ ) {
   abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::app); 
   abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::app);
 }
}

string Simulation::makeFilename( const string& basename, int index )
{
  ostringstream result;
  result << basename << index;
  return result.str();
}

This creates Abundances_0 and Abundances_IDs_0 but nothing else. I can write to those files. I can create the other filenames just fine, but the files just don't appear.

I'm probably missing something basic about streams, but I haven't been able to figure out what.

EDIT

The following code prints to screen the right filenames:

  for ( int d = 0; d < NUM_DEMES; d++ ) {
    abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::app);
    abundanceStream << "stuff\n";
    cout << makeFilename( "Abundances_", d ).c_str() << endl;
    abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::app);
    abHeaderStream << "more stuff\n";
    cout << makeFilename( "Abundances_IDs_", d ).c_str() << endl;
  }

But "stuff" and "more stuff" only appear in the Abundances_0 and Abundances_IDs_0.

+4  A: 

You are always using the same objects. You can either close the streams after "use" or use different objects for each file.

Steffen
Forgot this very important principle. Thank you.
Sarah
+4  A: 

Once you've opened a stream, another call to open will fail unless you close it first. So either add calls to abundanceStream.close() and abHeaderStream.close() at the end of each loop, or scope the stream objects inside the loop so you get a new one each time.

Mike Seymour
Thank you. This is obviously right!
Sarah