每当我重新运行代码后将数据写入文件时,文件的内容就会消失
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string username = "";
string path = "/Users/kishorejyothi/Desktop/C++/practice/list_usernames.txt";
ofstream file(path);
if(file.fail()){
cerr << "Failed process";
exit(1);
}
cout << "Enter a username: ";
cin >> username;
string full_username = username.append("@Abhinav.com");
if(username.empty()){
cout << "You didn't enter your username";
}
else{
cout << "Thanks for entering your preferred username." << endl;
cout << "Your username is now " << full_username;
}
file << username << endl;
file.close();
}
我希望文件将用户名写在不同的代码行上。
如果您希望文件保留以前的内容,则需要以
append
模式打开文件。
ofstream file(path, std::ios::app);