将字符串写入文件末尾(C++)

问题描述 投票:0回答:4

我已经形成了一个 C++ 程序,它有一个字符串,我想将其流式传输到现有文本文件的末尾。我所拥有的一切都是这样的:

void main()
{
    std::string str = "I am here";
    fileOUT << str;
}

我意识到还有很多要补充的,如果看起来我要求人们为我编码,我深表歉意,但我完全迷失了,因为我以前从未做过这种类型的编程。

我已经尝试过我在互联网上遇到的不同方法,但这是最接近的方法并且有点熟悉。

c++ string file streaming
4个回答
42
投票

使用

std::ios::app

打开文件
 #include <fstream>

 std::ofstream out;

 // std::ios::app is the open mode "append" meaning
 // new data will be written to the end of the file.
 out.open("myfile.txt", std::ios::app);

 std::string str = "I am here.";
 out << str;

9
投票

要将内容附加到文件末尾,只需在

ofstream
模式(代表append)下使用
app
(代表out文件流)打开文件。

#include <fstream>
using namespace std;

int main() {
    ofstream fileOUT("filename.txt", ios::app); // open filename.txt in append mode

    fileOUT << "some stuff" << endl; // append "some stuff" to the end of the file

    fileOUT.close(); // close the file
    return 0;
}

2
投票

以附加方式打开您的流,写入其中的新文本将写入文件末尾。


2
投票

我希望这不是你的全部代码,因为如果是,那么它有很多问题。

您写入文件的方式如下所示:

#include <fstream>
#include <string>

// main is never void
int main()
{
    std::string message = "Hello world!";

    // std::ios::out gives us an output filestream
    // and std::ios::app appends to the file.
    std::fstream file("myfile.txt", std::ios::out | std::ios::app);
    file << message << std::endl;
    file.close();

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.