c++ - 使用 remove() 函数删除文件时出错

标签 c++

我对 remove() 函数有疑问

先看例子就知道问题了

cout << "Please enter the phone number to remove" << endl << "Phone number: ";
string rphNumber;
cin >> rphNumber;
ifstream ifile("db/" + rphNumber + ".txt");
if(ifile)
  remove(("db/" + rphNumber + ".txt").c_str()); // the problem here
else
  cout << "failure" << endl;

问题在这一行(文件路径),虽然文件存在,函数总是返回-1

remove(("db/" + rphNumber + ".txt").c_str());

最佳答案

您的问题可能是您仍然有ifile在您尝试删除它的位置打开。某些操作系统不允许您删除打开的文件。另一种可能性是字符串 rphNumber末尾可能有一个换行符,您需要在组装文件名之前将其删除。 (我不记得 cin 是否这样做了。)

您的问题肯定您正在尝试确定文件系统操作是否有效。你不能那样做。在您进行测试和实际尝试执行操作之间,另一个进程可能会更改某些内容,从而使操作无法运行,即使您的测试表明可以运行。此外,能够打开文件与能够删除文件是不同的;您的硬盘驱动器上可能有很多文件可以打开但不能删除(例如 /dev/null )。

您只需执行 文件系统操作。它会通过返回值告诉您它是否有效。然后,当它不起作用时,你看看errno找出原因。 C效用函数strerror (包括 <cstring> )将转换 errno人类可读的错误消息的值。

综合起来,这是编写程序的正确方法:

cout << "Please enter the phone number to remove.\nPhone number: ";
string rphNumber;
cin >> rphNumber;
string fname("db/" + rphNumber + ".txt");

if (remove(fname.c_str()))
    cout << "Failed to delete '" << fname << "': " << strerror(errno) << '\n';
else
    cout << '\'' << fname << "' successfully deleted.\n";

顺便说一下,永远不要使用 endl ;如果'\n'不起作用,这意味着您的 streambufs 配置不正确。

关于c++ - 使用 remove() 函数删除文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781334/

相关文章:

c++ - 在 Linux 中,recv() 有效但 recvmsg() 无效

c++ - 为什么隐式类型转换在模板推导中不起作用?

c++ - C++中的线程序列化是什么意思?

c++ - 尝试将多个输出写入 .txt 文件 C++

c++ - 检测可移动驱动器(例如 USB 闪存驱动器)C/C++

c++ - 使用已编译版本的 openCV 时出错

c++ - C++中的返回类型

c++ - 有没有办法在 C++ 应用程序的多次执行中保存一个值?

c++ - 如何在 C++ 中初始化类的 priority_queue?

c++ - 将所有 double 转换为整数以获得更好的性能,这只是谣言吗?