在c++中删除文件和记录
Delete file and record in C++
我是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%更有可能:)),那么这是未定义的行为,即任何事情都可能发生(包括您看到的错误消息)。
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开始。
相关文章:
- 创建 Spdlog 异步文件记录器时遇到困难
- 分段错误:从文件中访问csv记录时转储了核心
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- c++ - 将大文件记录处理到 cpp 容器的最有效方法
- GDB / C++ - 根据循环条件将多个变量记录到输出文件中
- 在OSX中使用CGDisplayStream存储屏幕记录的特定文件路径
- 如何在文本文件中搜索员工记录(按名称)并仅显示其详细信息?
- 在二进制文件中删除记录
- C++同时记录到控制台和日志文件
- 如何让 doxygen 记录 .tcc 文件中定义的模板类?
- 为什么 fstream 打印出文件的最后一条记录
- QT控制台:记录所有stdin和stdout要文件
- 文件仅读取1个记录,然后到达文件的末尾,即使还有其他记录
- 将记录添加到文件中并将其读回
- C - 如何在文本文件中搜索学生记录
- 在特定字段中关键字搜索后,从文本文件中提取多个记录
- C 11中线程之间的共享文件记录
- 在数据库文件中创建10条空白记录
- 在C++中,文件中的下一条记录被非法更新
- Python的氧:一个段落记录文件和包