4

我正在尝试从我的 .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.
        }
    }
4

1 回答 1

2

这个:

rename( cUser + ".txt", cUser + ".txt" );

不正确有两个原因:

  1. 它是指针算术而不是字符串连接,因为cUser它是char[]
  2. 即使它是正确的 contanation 旧文件名和新文件名是相同的

没有理由使用strcpy_s()operator+用于std::string

const std::string oldFileName(user + ".txt");
const std::string newFileName(user + ".txt.new");

std::ofstream newFile(newFileName.c_str()); // c++11 allows std::string
if (newFile && newFile << line1)
{
    newFile.close();
    if (newFile)
    {
        if (0 == remove( oldFileName.c_str() ))
        {
            if (0 != rename( newFileName.c_str(), oldFileName.c_str() ))
            {
                // Handle rename failure.
            }
        }
        else
        {
            // Handle remove failure.
        }
    }
}

file.close()在尝试之前记住remove()

始终检查 IO 操作的结果,代码不确认是否file已打开或是否有任何getline()尝试成功:

ifstream file(user + ".txt");
if (file.is_open())
{
    string line1, line2;
    if (getline(file, line1) && getline(file, line2))
    {
        // Successfully read two lines.
    }
}
于 2013-05-13T10:07:10.073 回答