Search code examples
c++ioopenfoam

How do I append instead of overwrite here? (and how does this code open a file?)


I was going through an OpenFoam (v7) (C++) tutorial and came across this code for IO:

    // Create a custom directory and write an output file

    // Create the output path directory
    fileName outputDir = mesh.time().path()/"postProcessing";
    // Createe the directory
    mkDir(outputDir);
    // File pointer to direct the output to
        autoPtr<OFstream> outputFilePtr;
    // Open the file in the newly created directory
    outputFilePtr.reset(new OFstream(outputDir/"customOutputFile.dat");
    // Write stuff
    outputFilePtr() << "# This is a header" << endl;
    outputFilePtr() << "0 1 2 3 4 5" << endl;

Could somebody please help explain how this file is opened (I don't understand outputFilePtr.reset(new OFstream(outputDir/"customOutputFile.dat");) and how to append instead of overwrite? Adding std::ios::app doesn't seem to work here.

The constructor for openfoam-v7 is:

        OFstream
        (
            const fileName& pathname,
            streamFormat format=ASCII,
            versionNumber version=currentVersion,
            compressionType compression=UNCOMPRESSED,
            const bool append = false
        );

which can be found here and

141         outputFilePtr.reset( new OFstream(outputDir/"customOutputFile.dat",
142                                 ASCII,
143                                 currentVersion,
144                                 UNCOMPRESSED,
145                                  true) );

fails to error: ‘ASCII’ was not declared in this scope, error: ‘currentVersion’ was not declared in this scope and error: ‘UNCOMPRESSED’ was not declared in this scope.

Many thanks in advance for any help.


Solution

  • OFstream constructor:

    OFstream(
        const fileName& pathname,
        IOstreamOption  streamOpt = IOstreamOption(),
        const bool      append = false 
    )
    

    So:

    outputFilePtr.reset( new OFstream(outputDir/"customOutputFile.dat", 
                                      IOstreamOption(),
                                      true) );
    

    Edit: For the error with the old OpenFOAM version, it's most likely a namespace issue:

    outputFilePtr.reset( new OFstream(outputDir/"customOutputFile.dat",
                                      Foam::IOstream::ASCII
                                      Foam::IOstream::currentVersion,
                                      Foam::IOstream::UNCOMPRESSED,
                                      true) );