在c++中删除文件和记录

Delete file and record in C++

本文关键字:记录 文件 删除 c++      更新时间:2023-10-16

我是c++新手。我写了一个程序,允许用户添加文件到我的数据文件夹。但是现在我想允许用户删除文件。因此在下面的示例中,它将显示来自data文件夹的可用文件列表。用户通过输入数字(例如[i])选择文件,将该文件从列表中删除,同时删除数据文件夹中的文件。我试过写代码来删除它,但我得到了这个错误"调试断言失败"。我的删除有什么问题吗?

case 'D':
case 'd':
    myfiles = getFiles();
    cout << "Current available objects:" << endl;
    for (int i = 0; i < myfiles.size(); i++)
        cout << '[' << i << ']' << ' ' << myfiles[i] << endl;
    cout << endl << "Enter file number to delete or "end" to exit:";
    while (cin >> str)
    {
        if (str == "end")
            break;
        input = str2int(str);
        if (input >= 0 && input < myfiles.size())
        {
            //Delete object
            newname = ExePath() + "/data/" + myfiles[input];
            name = new char[newname.size() - 1];
            strcpy(name, newname.c_str());
            remove(name);
            //Print out the available objects
            cout << "nCurrent available objects:" << endl;
            for (int i = 0; i < myfiles.size(); i++)
                cout << '[' << i << ']' << ' ' << myfiles[i-1] << endl;
            cout << endl << "Enter file number to delete or "end" to exit:";
        }
        else cout << "Invalid input." << endl;
    }
    break;

我想是这个循环:

 for (int i = 0; i < myfiles.size(); i++)
                cout << '[' << i << ']' << ' ' << myfiles[i-1] << endl;

i为0时,则试图访问myfiles[-1]。如果myfiles不是一个非常奇怪类的对象,它以一种不寻常的方式重载operator[],而是一个正常的std::vector(99%更有可能:)),那么这是未定义的行为,即任何事情都可能发生(包括您看到的错误消息)。

作为旁注,您正在执行指针操作,而不是始终如一地使用真正的c++字符串(即std::string对象)。这是令人惊讶的,因为您似乎已经有了std::string (newname),并且您似乎知道如何将它与需要char const *的(旧/遗留/C)函数一起使用,即与其c_str()成员函数。为什么不直接写remove(newname.c_str())呢?

至少你应该使用

name = new char[newname.size() + 1];
不是

name = new char[newname.size() - 1];

无论如何,我不认为有必要复制字符串。同样会失败的还有:

myfiles[i-1]

在第二个循环中,因为它从0开始。