使用 ofstream 追加文件内容

27

我在将文本追加到文件时遇到了问题。我以追加模式打开了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构造函数是什么?


3
std::ofstream()构造函数的文档中已经很好地描述了这一点。 - πάντα ῥεῖ
2个回答

47

我使用一个非常方便的函数(类似于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
std::ios_base::appstd::io::app有什么区别? - Alexander
1
app 在每次写入之前都会结束,而 ate 则是在打开后立即寻找结尾。 - Hope
+1 for PHP参考。PHP在某些地方可能会被讨厌,但它有很多有用的小函数,可以让开发人员的生活更轻松 :) - AntonioCS

18

ofstream的构造函数中,使用ios_base::app代替ios_base::ate作为ios_base::openmode


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接