我对 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/