CFD Online Discussion Forums

CFD Online Discussion Forums (https://www.cfd-online.com/Forums/)
-   OpenFOAM Programming & Development (https://www.cfd-online.com/Forums/openfoam-programming-development/)
-   -   How does one initialise an OFstream in the constructor? (https://www.cfd-online.com/Forums/openfoam-programming-development/91625-how-does-one-initialise-ofstream-constructor.html)

bigphil August 17, 2011 08:17

How does one initialise an OFstream in the constructor?
 
Hi,


I have a class which contains an OFstream member
Code:

OFstream outFile_;
For serial runs I normally initialise this member in the constructor using the quick method:
Code:

Foam::myClass::myClass
(
...
constructor arguments
...
)
:
outFile_("fileName")
{
...
main constructor here
...
}

But for parallel runs, I only want the master processor to create this file.

I have tried initialise the OFstream object in the main constructor (not the quick way above), but it is wrong:
Code:

if(Pstream::master())
{
outFile_ = new OFstream("fileName");
}

Could anybody let me know how I might do this correctly?


Philip

marupio August 17, 2011 14:33

You can use the conditional operator in initialization lists. Here's an example from my code:

Code:

    convergence_
    (
        dict_.found("convergence")
      ? readScalar(dict_.lookup("implicitConvergence"))
      : defaultConvergence_
    ),

The syntax (with typical OF whitespace) is:
Code:

    item
    (
        trueOrFalseExpression
      ? useThisIfTrue
      : useThisIfFalse
    ),

The trick is both the useThisIfTrue and useThisIfFalse have to be the same type of object. So you probably have to create a null OFstream for non-master processors, or something like that.

-Dave

bigphil August 18, 2011 09:48

Dave,


Thanks, this looks like what I need.

I tried:
Code:

outFile_
(
Pstream::master()
? "fileName"
: NULL
)

This compiles fine but gets the run-time error:
Code:

error
what():  basic_string::_S_construct NULL not valid
terminate called after throwing an instance of 'std::logic_error'


So as a work-around, I have done this:
Code:

outFile_
(
Pstream::master()
? "fileName"
: "slaveNullFile"
)

This does the job but an empty slaveNullFile is created.


Thanks for the help,
Philip


All times are GMT -4. The time now is 09:27.