0

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.

Sarah
  • 1,614
  • 1
  • 23
  • 37
  • What is the value of result.str() per each invocation? and what is NUM_DEMES set to? – Chris K Nov 12 '09 at 19:43
  • what is the value of NUM_DEMES? – Eli Bendersky Nov 12 '09 at 19:44
  • Sorry. NUM_DEMES = 2, and d is incrementing properly. Result.str() also checks out fine (i.e., cout << result.str() prints what it should, and printing the results of makeFilename(...) also gives the right filenames). – Sarah Nov 12 '09 at 19:48

2 Answers2

4

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

Steffen
  • 2,888
  • 19
  • 19
4

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
  • 249,747
  • 28
  • 448
  • 644