我写了一个函数,它应该删除一个目录及其中所有的文件和文件夹,但是它出了一些问题。为了测试这个函数,我特意创建了一个实验目录,该目录包含一些文件和一个子目录。而这个子目录也包含1或2个文件。我的函数成功地删除了子目录及其中的所有文件。并且主目录中的所有文件也被成功删除了。但当函数开始尝试删除主目录时,它却失败了。似乎rmdir返回的不是0,我不知道为什么,因为子目录可以成功删除。 作为参数,它接受像"D:\new\"这样的字符串。 这里的new是应该与其中所有内容一起删除的主目录。下面是这个函数的代码:
void OperationsWithDirectories::RemovingCycle(string _path)
{
string wayToFile; // string to hold the path to the directory without mask
string deletedFile; // string which would hold the way to deleting file
wayToFile = _path;
_path += "*.*"; // add a mask to the _path string
_finddata_t* fileinfo = new _finddata_t;
long done = _findfirst(_path.c_str(), fileinfo);
int IsContinue = done;
while (IsContinue != -1)
{
deletedFile = wayToFile + fileinfo->name;
if (fileinfo->attrib == _A_SUBDIR)
{
if (strcmp(fileinfo->name, ".") != 0 && strcmp(fileinfo->name, "..") != 0)
{
cout << "\nEnter subdirectory\n";
RemovingCycle(wayToFile + fileinfo->name + "\\"); //recursive func wich would start, if subdirectory is exist
cout << "\nOutta subdirectory\n";
}
}
else
{
if ((remove(deletedFile.c_str())) != 0)
cout << "\n\n ERROR IN FILE DELETING\n\n";
else
cout << endl << deletedFile << " - was deleted";
}
IsContinue = _findnext(done, fileinfo);
}
if ((_rmdir(wayToFile.c_str())) != 0)
cout << "\n\nERROR IN DIRECT - " << wayToFile << " DELETING\n\n";
else
cout << "\ndir - " << wayToFile << " was deleted succesfully\n";
}