boost::filesystem::remove_all(path)如何工作

How does boost::filesystem::remove_all(path) work?

本文关键字:何工作 工作 filesystem path all boost remove      更新时间:2023-10-16

我正在尝试使用 boost::filesystem::remove_all(path) 从特定路径中删除所有目录、子目录和包含的文件。我还想显示一条错误消息,以防文件在另一个程序中打开。在这种情况下,boost::filesystem::remove_all(path)会引发异常吗?

还是有其他方法可以实现这一目标?

不适合评论,所以我作为答案发布

只需查看来源:http://www.boost.org/doc/libs/1_55_0/libs/filesystem/src/operations.cpp

  BOOST_FILESYSTEM_DECL
  boost::uintmax_t remove_all(const path& p, error_code* ec)
  {
    error_code tmp_ec;
    file_type type = query_file_type(p, &tmp_ec);
    if (error(type == status_error, tmp_ec, p, ec,
      "boost::filesystem::remove_all"))
      return 0;
    return (type != status_error && type != file_not_found) // exists
      ? remove_all_aux(p, type, ec)
      : 0;
  }

remove_all_aux在上面几行定义,remove_file_or_directoryremove_fileremove_directory等等。基元操作为:

# if defined(BOOST_POSIX_API)
... 
#   define BOOST_REMOVE_DIRECTORY(P)(::rmdir(P)== 0)
#   define BOOST_DELETE_FILE(P)(::unlink(P)== 0)
...
# else  // BOOST_WINDOWS_API
...
#   define BOOST_REMOVE_DIRECTORY(P)(::RemoveDirectoryW(P)!= 0)
#   define BOOST_DELETE_FILE(P)(::DeleteFileW(P)!= 0)
...
# endif

删除锁定文件的行为将取决于您的平台将提供的任何行为。

我正在发布一些代码示例来澄清这个问题。有两种情况。

在第一种情况下,我使用 remove_all 函数从某个路径中删除整个目录,然后在同一路径上创建一个新目录:

try
{
if(exists(directory_path))
{
   remove_all(directory_path);
}
    create_directory(directory_path);   
}
catch(filesystem_error const & e)
{
    //display error message 
}

这就像预期的那样工作,但是我有第二种情况,我尝试从路径中删除某些文件夹,然后创建新目录:

try
    {
        if(exists(directory_path))
        {
            for ( boost::filesystem::directory_iterator itr(directory_path); itr != end_itr; itr++)
            {
                std::string folder = itr->path().filename().string();
                if(folder == FOLDER1 || folder == FOLDER2 || folder == FOLDER3)     
                      remove_all(itr->path());
            } 
         }          
        create_directory(directory_path);   
    }
    catch(filesystem_error const & e)
    {    
                 //display error message
    }

在这种情况下,如果文件在另一个程序中打开,则不会引发异常。文件只是被删除。为什么会这样?

C++中使用 Boost 库删除目录的示例程序

#include <boost/filesystem.hpp>
int main() {
    // replace with the name of the directory you want to delete
    const std::string dirname = "my_directory"; 
    boost::system::error_code ec;
    boost::filesystem::remove_all(dirname, ec);
    if (ec) {
        std::cerr << "Error deleting directory: " 
                  << ec.message() << std::endl;
        return 1;
    }
    return 0;
}

请注意,remove_all()函数还可用于删除文件和非空目录。如果只想删除空目录,则可以改用boost::filesystem::remove()。此外,请确保您在项目中安装了 Boost 库并正确链接。

这取决于您调用的remove_all的重载; 这在函数的文档中有明确的记录。 (不清楚的是,如果您使用通过错误代码报告错误的函数,该函数是继续,还是在第一个错误后返回?