我怎么可以追加到一个文本文件

我怎么可以追加到一个文本文件

本文介绍了我怎么可以追加到一个文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C ++编写一个程序,从用户接受文本,并将其保存到使用文件句柄的文本文件。以下是该计划的一些片断:

I have a program written in C++ which accepts text from a user and saves it to a text file using file handles. Here are snippets of the program:

程序工作正常。它唯一的问题是,它不追加文本到文本文件。相反,它删除所有现有的文本,并只保存新的文本。

The program works fine. The only problem with it is that it does not append the text to the text file. Rather, it "removes" all the existing text and only saves the new text.

这是保存在程序的previous会话文本被丢弃,新的文本保存来代替。我怎么能解决这个问题吗?

That is, the text saved in a previous session of the program is discarded and the new text is saved instead. How can I solve this problem please?

推荐答案

打开文件时包括 O_APPEND 标记。请参阅。

Include the O_APPEND flag when opening the file. See the reference page for _open().

由于这是C ++考虑使用代替。这是类型安全的,除去具有指定的参数的长度被写入到文件的要求:

As this is C++ consider using an ofstream instead. These are type-safe and remove the requirement of having to specify the length of the arguments being written to the file:

std::ofstream out(full_path, std::ios_base::app);
if (out.is_open())
{
    out << "----Session----\n\n"
        << "Date/Time: " << datetime << "\n\n"
        << "Text: " << text << "\n\n\n\n";
}

这篇关于我怎么可以追加到一个文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 02:31