Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用remove()函数删除文件时出错_C++ - Fatal编程技术网

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

C++ 使用remove()函数删除文件时出错,c++,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/" + rphN

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

如果
remove
失败,它将设置
errno
,并返回
-1
。我不完全清楚您如何确定它是否失败,因为您实际上没有将返回值存储在变量中

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

int rc = remove(("db/" + rphNumber + ".txt").c_str());
if (rc < 0)
    perror ("could not remove file");
int rc=remove((((“db/”+rphNumber+“.txt”).c_str());
if(rc<0)
perror(“无法删除文件”);
您的问题可能是在尝试删除文件时,仍有
ifile
处于打开状态。某些操作系统不允许删除打开的文件。另一种可能性是字符串
rphNumber
的末尾可能有一个新行,您需要在组装文件名之前去掉它。(我不记得cin是否这样做了。)

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

您只需执行文件系统操作。它将告诉您它是否工作,以及它的返回值。然后,当它不起作用时,请查看
errno
,找出原因。C实用程序函数
strerror
(包括
)将
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";
cout>r编号;
字符串fname(“db/”+rphNumber+“.txt”);
if(删除(fname.c_str())

库特@Michael Goldshteyn:不幸的是,没有错误message@LionKing您正在使用哪个平台?@FailedDev::我正在使用Visual Studio 2010和Windows 7paxdiablo::不幸的是,没有出现错误消息,但是函数return-1I我不建议使用
perror
,因为它让你在报告失败的操作和报告无法操作的文件名之间做出选择,而你真的应该报告两者。@Zack,我不建议将此作为生产修复,只是为了让临时调试代码找出问题。在任何情况下,你都可以把这两项都放进一个字符串,传递给<代码> PrRor 。我猜这远不像C++中那样令人恼火。好吧,除了引擎盖下内存分配可能会出错之外。这也许不值得担心。正如您所说,这是临时调试代码。错误消息是::未能删除c://fileName.txt:权限被拒绝错误消息是::未能删除c://fileName.txt:权限被拒绝这不正确,因为程序正在尝试删除名为“db”的目录中的文件。它到底说了什么?
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";