C++ 使用 ofstream 附加到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26084885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:31:01  来源:igfitidea点击:

appending to a file with ofstream

c++

提问by Wojtek

I have a problem with appending a text to a file. I open an ofstreamin append mode, still instead of three lines it contains only the last:

我在将文本附加到文件时遇到问题。我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!

So what's the correct ofstreamconstructor for appending to a file?

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

回答by dynamic

I use a very handy function (similar to PHP file_put_contents)

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

When you need to append something just do:

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

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

Using this function you don't need to take care of opening/closing. Altho it should not be used in big loops

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

回答by macfij

Use ios_base::appinstead of ios_base::ateas ios_base::openmodefor ofstream's constructor.

使用ios_base::app代替ios_base::ateas ios_base::openmodeforofstream的构造函数。