filesystem库是一个可移植的文件系统操作库,使用POSIX标准表示文件系统路径,使得C++具有了类似于脚本语言的功能,可以跨平台操作目录、文件,写出通用脚本。
使用filesystem组件,需要包含头文件 <boost/filesystem.hpp> 即: #include <boost/filesystem.hpp> using namespace boost::filesystem;
01 -- path类
路径表示
char str[] = 'the path is (/root).'; // 设置字符串“the path is (/root).” str[0] = 't', str[1] = 'h', ... , str[13] = '/', ... , str[17] = 't', str[18] = ')', ...
path p(str + 13, str + 14); // 取字符串str中的 str[13], 截取方式是 start_str = str[13], end_str = str[14], new_str = str[13], 则 p = '/'
assert(!p.empty()); // 判断p是否为空
p /= ''etc; // 符号‘/=’是字符串连接,类似于python中的 ‘+’, 得到新字符串为: ‘/etc’; 具有相同操作的还有 += 符号,但是不加路径分隔符
string filename = 'xineted.conf';
p.append(filename.begin(), filename.end()); // 向 p 中追加字符序列,得到 new_str = '/etc/xinetd.conf'; 具有相同操作的还有 concat()函数
system_complete(p); // 返回p的当前路径
路径处理
path p('/usr/local/include/xxx.hpp');
cout<<p.string()<<endl; // 返回以字符串格式返回路径表示
cout<<p.parent()<<endl; // 返回path中的父路径,即上一层目录
p.stem() 返回全文件名; p.filename() 返回没有文件扩展名的文件名; p.extension() 返回文件扩展名
p.is_absolute() 判断p是不是绝对路径,返回 True or Flase
p.root_name() 返回根目录名; p.root_directory() 返回根目录; p.root_path() 返回根路径; 'c:/xx/yy' -> 'c:' ; '/' ; 'c:/'
p.ralative_path() 返回相对路径, 相当于 path - root_path
has_filename() 判断路径是否有文件名 has_parent_path() 判断是否有父路径
remove_filename() 删除路径中最后的文件名,把path变成纯路径表示
replace_extension() 变更文件的扩展名 p.replace_extension('txt') xx.cpp -> xx.txt
路径的迭代表示
path p = '/boost/tools/libs';
for(auto& x, p) // 可以把 for 变成 BOOST_FOREACH
{
cout<<x<<;
}
>> /
>> boost
>> tools
>> libs
02 -- 文件属性
fs::initial_path() // 返回程序启动时(进入main函数)的绝对路径
fs::current_path() // 返回当前路径(绝对路径)
file_size(file) // 以字节为单位返回文件大小
last_write_time(file) // 返回文件的最后修改时间
last_write_time(file, time) // 更新修改时间
space_info('/home/fs') // 返回当前目录下各文件的磁盘占用情况
exists(dir) // 判断dir是否存在
is_directory(dir) // 判断是否是一个dir
is_empty(dir) // 判断路径下是否有文件,或判断文件是否为空
remove(path) // 移除空目录和空文件
remove_all(path) // 所有文件都移除