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

时间:2011-10-15 23:21:02

标签: 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());

2 个答案:

答案 0 :(得分:1)

如果remove失败,则会设置errno以及返回-1。我并不完全如何你确定它失败了,因为你实际上并没有将返回值存储在一个变量中。

但是,假设 返回-1,则打印errno,这样您就可以知道实际错误是什么,例如:

int rc = remove(("db/" + rphNumber + ".txt").c_str());
if (rc < 0)
    perror ("could not remove file");

答案 1 :(得分:1)

您的问题可能是您在尝试删除它时仍然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配置不正确。