boost 文件操作

本文介绍了如何利用Boost库进行文件和文件夹的管理,包括判断存在性、删除、重命名、创建、复制以及遍历文件夹等操作。通过示例代码展示了Boost::filesystem的API用法,为开发者提供了更便捷的文件系统操作方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果要简单处理文件和文件夹的时候(删除、重命名等),使用Windows的系统函数会十分麻烦,可以尝试一下使用Boost库来进行处理

头文件

#include <boost/filesystem.hpp>

如果要获得每次处理的结果错误码,需要加上头文件:

#include <boost/system/error_code.hpp>
boost::system::error_code err;

如果不需要的话只需要把err去掉

以下路径均为绝对路径

基础类型

boost::filesystem::path filepath;

判断文件/文件夹是否存在:

boost::filesystem::exists(filepath, err)
//true 存在
//false 不存在

判断文件路径是否文件夹:

boost::filesystem::is_directory(filepath, err)
//true 是
//false 不是

删除文件:

boost::filesystem::remove(filepath, err)
//true 删除成功
//false 删除失败

重命名文件:

boost::filesystem::rename(oldname, newname, err)

创建文件/文件夹:

boost::filesystem::create_directories(filepath, err)

获取当前路径:

boost::filesystem::current_path()

复制文件/文件夹:

boost::filesystem::copy(frompath, topath)

遍历文件夹:

boost::filesystem::directory_iterator fileIter(filepath);
boost::filesystem::directory_iterator enditer;
for (; fileIter != enditer; ++fileIter) {
    //每个文件的路径
    fileIter->path();
}

判断文件是否存在父目录

filepath.has_root_directory()
//true 存在父目录
//false 不存在

获取当前文件路径的父目录

filepath.parent_path()

判断当前文件路径是否是 ‘.’/’…’(遍历的时候可能用得上):

filepath.filename_is_dot()
filepath.filename_is_dot_dot()

如果需要,还可以将文件路径转成string或wstring

filepath->string()
filepath->wstring()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值