我正在尝试从我的 .txt 文件中删除一行。该文件包含有关该帐户的所有信息。
该行显示“newAccount”并在创建帐户时创建。我使用它是为了在您第一次登录时启动教程。教程结束后我想删除此行,以便下次登录时您不会获得教程。
这是代码片段:(不起作用)
void loginScreen(string user){
system("CLS");
cout << "Hello " + user << endl;
ifstream file(user + ".txt");
string line1;
getline(file, line1);
// Begin reading your stream here
string line2;
getline(file, line2);
if(line2 == "newAccount"){
cout << "Your account is new";
char cUser[200];
strcpy_s(cUser, user.c_str());
std::ofstream newFile( user + ".txt.new" );
// Do output...!!!!!!!
newFile << line1;
newFile.close();
if ( newFile ) {
remove( cUser + ".txt" );
rename( cUser + ".txt", cUser + ".txt" );
} else {
std::cerr << "Write error on output" << std::endl;
}
}
}
编辑:
我已将我的代码编辑为此,它仍然无法正常工作:
const string oldFileName(user + ".txt");
const string newFileName(user + ".txt.new");
std::ofstream newFile( user + ".txt.new" );
// Do output...!!!!!!!
newFile << line1;
newFile.close();
if(line2 == "newAccount"){
ofstream newFile(newFileName.c_str()); // c++11 allows std::string
if (newFile){
if (0 == remove( oldFileName.c_str() )){
if (0 != rename( newFileName.c_str(), oldFileName.c_str() )){
// Handle rename failure.
}
}else{
// Handle remove failure.
}
}