开发者

Dynamic output filenames (C++)

开发者 https://www.devze.com 2022-12-11 11:52 出处:网络
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).

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( "Abundanc开发者_C百科es_IDs_", d ).c_str() << endl;
  }

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号