如何相应地将每个数据输出到文件?

时间:2012-04-06 06:47:00

标签: c++ file outputstream ofstream file-io

struct GPattern() {
    int gid;
    ....
}
class Example() {
public:
    void run(string _filename, unsigned int _minsup);
    void PrintGPattern(GPattern&, unsigned int sup);
    ....
};

Eample::run(string filename, unsigned int minsup) {
    for(...) {    // some condition
        // generate one GPattern, and i want to ouput it
        PrintGPattern(gp, sup);
    }
}

Example::PrintGPattern(GPattern& gp, unsigned int sup) {
    // I want to ouput each GPattern to a .txt file
}

run用于相应地生成GPattern

我想要输出到文件的是一些重建原始GPattern的文本。

我无法提前存储所有GPattern并输出所有这些内容。我在生成文件时必须输出一个GPattern,但我不知道如何实现它。

我曾尝试在课程ofstream outGPatter("pattern.txt")中声明Example,但这没有用......

3 个答案:

答案 0 :(得分:1)

嗯,ofstream是正确的方法:

Example::PrintGPattern(GPattern& gp, unsigned int sup) {
    ofstream outGPattern("pattern.txt")

    outGPattern << gp.gid; << " " << gp.anotherGid << " " ....

    outGPattern.close()
}

您是否看过pattern.txt的正确位置?它应该位于.exe所在的文件夹中,或者位于所有.h和.cpp文件所在的文件夹中(至少对于VS)。

如果要将所有模式写入同一文件,则需要确保附加(而不是覆盖)pattern.txt

  

ofstream outGPattern(“pattern.txt”,ios :: app)

因此,您可以在程序开始时首先创建没有ios :: app(清除文本文件)的ofstream。然后使用ios :: app构建所有其他的流以附加新文本,而不是覆盖它。

或者,您可以将ofstream设为Example的成员变量。然后你只构造一次。

答案 1 :(得分:1)

我认为您可以使用追加模式,例如:

ofstream outGPattern;
outGPattern.open("GPattern.txt", ios::app);

答案 2 :(得分:1)

我看到它的方式,你想追加多个GPattern信息,你只需要在构造函数中将I / O模式设置为ios::app。 / p>

struct GPattern {
  int gid;
  friend ostream& operator <<(ostream& o, GPattern gp) {
    return o << "(gid=" << gp.gid << ")";
  }
  ...
}

Example::PrintGPattern(GPattern& gp, unsigned int sup) {
  ofstream fout("pattern.txt", ios::app)
  fout << gp << endl;
  fout.close()
}