我创建了一个在 .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;
}
Run Code Online (Sandbox Code Playgroud)