【问题标题】:appending to a file with ofstream [duplicate]使用 ofstream 附加到文件 [重复]
【发布时间】:2014-09-28 12:34:11
【问题描述】:

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

【问题讨论】:

标签: c++


【解决方案1】:

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

使用此功能,您无需关心打开/关闭。尽管如此,它不应该在大循环中使用

【讨论】:

  • std::ios_base::appstd::io::app有什么区别?
  • app 会在每次写入前结束,而 ate 打开并会在打开后立即结束。
  • +1 供 php 参考。 PHP 在某些地方可能会被讨厌,但它有许多像这样的有用的小功能,让开发人员的生活更轻松:)
【解决方案2】:

使用ios_base::app 而不是ios_base::ate 作为ios_base::openmode 用于ofstream 的构造函数。

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 2015-07-02
    • 1970-01-01
    • 2018-10-18
    • 2016-03-25
    相关资源
    最近更新 更多