附加到ofstream的文件

时间:2014-09-28 12:34:12

标签: c++

我在将文本附加到文件时遇到问题。我在追加模式下打开ofstream,而不是三行只包含最后一行:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ofstream file("sample.txt");
    file << "Hello, world!" << endl;
    file.close();

    file.open("sample.txt", ios_base::ate);
    file << "Again hello, world!" << endl;
    file.close();

    file.open("sample.txt", ios_base::ate);
    file << "And once again - hello, world!" << endl;
    file.close();

    string str;
    ifstream ifile("sample.txt");
    while (getline(ifile, str))
        cout << str;
}

// output: And once again - hello, world!

那么附加到文件的正确ofstream构造函数是什么?

2 个答案:

答案 0 :(得分:13)

我使用了一个非常方便的功能(类似于PHP file_put_contents)

// Usage example: filePutContents("./yourfile.txt", "content", true);
void filePutContents(const std::string& name, const std::string& content, bool append = false) {
    std::ofstream outfile;
    if (append)
        outfile.open(name, std::ios_base::app);
    else
        outfile.open(name);
    outfile << content;
}

如果您需要附加某些内容,请执行以下操作:

filePutContents("./yourfile.txt","content",true);

使用此功能,您无需打开/关闭。虽然不应该在大循环中使用

答案 1 :(得分:9)

ios_base::app的构造函数使用ios_base::ate代替ios_base::openmode ofstream