c ++从.text文件中删除行

时间:2013-05-13 09:11:15

标签: c++ file line

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

1 个答案:

答案 0 :(得分:2)

此:

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

不正确有两个原因:

  1. 它是指针算术而不是字符串连接,因为cUserchar[]
  2. 即使它是正确的连接旧文件名和新文件名是相同的
  3. 没有理由使用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.
        }
    }