附加到ofstream的文件

Woj*_*tek 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!
Run Code Online (Sandbox Code Playgroud)

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

dyn*_*mic 15

我使用了一个非常方便的函数(类似于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;
}
Run Code Online (Sandbox Code Playgroud)

当你需要追加一些东西时:

filePutContents("./yourfile.txt","content",true);
Run Code Online (Sandbox Code Playgroud)

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


mac*_*fij 10

使用ios_base::app,而不是ios_base::ate作为ios_base::openmodeofstream的构造.