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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6932409/
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 20:56:46  来源:igfitidea点击:

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

c++stringfilestreaming

提问by ked

I have a program already formed that has a string that I want to stream to the end of an existing text file. All of what little I have is this: (C++)

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

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

I realize there is much to be added to this and I do apologize if it seems I am asking people to code for me, but I am completely lost because I have never done this type of programming before.

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

I have attempted different methods that I have come across the internet, but this is the closest thing that works and is somewhat familiar.

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

回答by Chad

Open your file using std::ios::app

使用打开您的文件 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;

回答by Seth Carnegie

To append contents to the end of files, simply open a file with ofstream(which stands for out file stream) in appmode (which stands for append).

要将内容追加到文件末尾,只需打开一个文件,其中ofstream(代表out 文件流) in appmode (代表append)。

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

回答by Mike Bailey

I hope that isn't your whole code because if it is, there's lots of things wrong with it.

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

The way you would write out to a file looks something like this:

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

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

回答by Blindy

Open your stream as append, new text written to it will be written at the end of the file.

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