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_directory
、remove_file
、remove_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
的重载; 这在函数的文档中有明确的记录。 (不清楚的是,如果您使用通过错误代码报告错误的函数,该函数是继续,还是在第一个错误后返回?
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?