【问题标题】:How do I append instead of overwrite here? (and how does this code open a file?)我如何在这里追加而不是覆盖? (以及此代码如何打开文件?)
【发布时间】:2020-12-16 02:23:39
【问题描述】:

我在阅读 OpenFoam (v7) (C++) 教程时遇到了这个 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;

谁能帮忙解释一下这个文件是怎么打开的(我不明白outputFilePtr.reset(new OFstream(outputDir/"customOutputFile.dat");) 以及如何追加而不是覆盖?添加 std::ios::app 似乎在这里不起作用。

openfoam-v7的构造函数是:

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

可以在here找到 和

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

出错:未在此范围内声明“ASCII”, 错误:“currentVersion”未在此范围内声明,并且 错误:未在此范围内声明“未压缩”。

非常感谢您的任何帮助。

【问题讨论】:

  • 如果你用 C 标记一个 C++ 问题,你会吸引很多 C 专家,他们会找借口拒绝或关闭你的问题。
  • 如果OFstream 类似于std::ofstream。然后它使用非默认流构造函数打开文件,并且构造函数应该有额外的参数来指定模式。请参阅OFstream 文档。另请参阅 std::ofstream 文档。
  • 哇,那个项目的代码组织很糟糕。这是声明该类型的OFstream.h - 您可能拥有该类型的本地副本并且可以阅读。看看构造函数。提示:第 106 行。

标签: c++ io openfoam


【解决方案1】:

OFstream构造函数:

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

所以:

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

编辑:对于旧 OpenFOAM 版本的错误,很可能是命名空间问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2016-12-28
    • 2020-11-28
    • 1970-01-01
    • 2010-12-16
    • 2022-01-01
    • 2011-11-23
    • 1970-01-01
    相关资源
    最近更新 更多