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

Writing a string to the end of a file (C++)

本文关键字:c++ 字符串 文件      更新时间:2023-10-16

我有一个已经形成的c++程序,其中有一个字符串,我想将其流式传输到现有文本文件的末尾。我仅有的一点东西就是:

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

我意识到有很多东西要添加到这个,我很抱歉,如果它似乎是我要求人们为我编码,但我完全迷路了,因为我从来没有做过这种类型的编程之前。

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

使用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;

要在文件末尾附加内容,只需以app模式(代表附加)以ofstream(代表out file stream)打开文件。

#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;
}

打开你的流作为追加,写入到它的新文本将被写入到文件的末尾

我希望这不是你的全部代码,因为如果是的话,有很多地方是错误的。

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

#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;
}