附加到一个文件withstream [英] appending to a file with ofstream

查看:82
本文介绍了附加到一个文件withstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将文字附加到档案时发生问题。我在追加模式下打开 ofstream ,而不是三行它只包含最后一行:

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

#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 构造函数到文件?

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

推荐答案

我使用一个非常方便的函数(类似于PHP file_put_contents)

I use a very handy function (similar to 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

这篇关于附加到一个文件withstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆