C++ 将字符串添加到现有文本文件

标签 c++ text-files memory-address

下面的代码生成一个以日期为标题的文本文件,并将在命令提示符下输入的内容写入 .txt。问题是,一旦我第二次运行代码,它会删除​​之前写入的内容并写入新输入的内容。如果文本文件已经存在,我想保留之前写的内容,跳下两行添加新的 Material 。有什么想法吗?

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

void main()
{
    time_t now = time(0);
    tm *ltm = localtime(&now);
    int day = ltm->tm_mday;
    int month = 1 + ltm->tm_mon;
    int year = 1900 + ltm->tm_year;
    std::string d = std::to_string(day);
    std::string m = std::to_string(month);
    std::string y = std::to_string(year);
    std::string info;
    std::getline (std::cin, info); 
    std::ofstream notes(m + d + y + ".txt", std::ios::out);
    if (notes.is_open())
    {
        notes << info;
    }
    else
    {
        std::cout << "couldn't make file";
    }
}

最佳答案

改变你的

std::ofstream notes(m + d + y + ".txt", std::ios::out);

为了

std::ofstream notes(m + d + y + ".txt", std::ios::app);

这样你就可以在文件末尾追加新行

有关写入模式的更多信息:Check this link

关于C++ 将字符串添加到现有文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149245/

相关文章:

c++ - 在 C++ 中找出随机数生成器的种子

c - 将文件格式化为每行 5 个数字

c - 如何确保两个地址的最低有效 4 位相同?

c++ - 在 C++ 中通过引用将地址传递给类并从那里传递给它的 "child-class"

c++ - 在 C++ 中使用 shared_ptr 的双重释放错误

c++ - 如何从 C++ 加载项获取 excel 版本

c++ - 我应该存储整个对象还是指向容器中对象的指针?

vim - 在 VIM 中隐藏、显示和仅将功能应用于具有恢复能力的可见行?

python - 我正在尝试使用 for 循环打印 .txt 文件的多行。它总是缺少最后三行

c++ - 为什么 char 在数组中占用的空间似乎比它本身占用的空间更多