繁体   English   中英

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

[英]How does boost::filesystem::remove_all(path) work?

我试图使用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
    }

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

这取决于你调用remove_all重载; 这个功能的文档中清楚地记录了这一点。 (不清楚的是,如果你使用通过错误代码报告错误的函数,函数是继续,还是在第一次错误后返回?)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM