c++ - 如何在 C++ 中保存 .txt 文件?

标签 c++ visual-c++

<分区>

我在 .txt 文件中创建了代码编写内容并从中读取。但如果我关闭程序并重新开始写入,它会删除旧文本并用新文本覆盖它。

有没有办法不覆盖已有的数据?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void check() {

    string text;
    ifstream file;
    file.open("test.txt");
    getline(file, text);

    if (text == "") {
        cout << "There's no data in file" << endl;
    } else {
        cout << "File contains:" << endl;
        cout << text << endl;
    }
}

int main() {

    check();

    string text;
    ofstream file;
    file.open("test.txt");
    cout << "Type some text" << endl;
    getline(cin, text);
    file << text;

    return 0;
}

最佳答案

您需要像下面的示例一样以“追加”模式打开文件

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("yourfile.txt", std::ios_base::app);//std::ios_base::app
  outfile << "your data"; 
  return 0;
}

您可以在此处阅读有关 fstream 标志的信息
http://www.cplusplus.com/reference/fstream/fstream/open/

关于c++ - 如何在 C++ 中保存 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33588266/

相关文章:

c++ - 在Linux中,等效于在c/c++中打开物理驱动器的句柄并写入MBR的方法是什么?

c++ - 我如何将 String 对象转换为 UTF8CHAR 指针?

c++ - 提取脏矩形 RGB 像素缓冲区数据 DirectX

c++ - 在 C++ 中使用枚举

C++ SDL2圆周运动

c++ - wxWidgets 中的 XP 视觉风格?

C++,sprintf_s 的包装函数

c++ - 在 IMMDeviceEnumerator 上调用 SAFE_RELEASE 时崩溃

c++ - 函数 CWnd::CreateControl 成功,但 m_hWnd 为 NULL

c++ - 如何检测库是否使用 XP 兼容性 (v120_xp)?