以下知识点转自:点击打开原文链接
今天拿起手要用C++写个小工具,从指定的目录递归遍历文件,然后做一下处理。又翻了一下boost的filesystem库。小结一下,希望能加深印象,免得下次又要查看文档。
1. path对象就是一个跨平台的路径对象。有许多方法访问路径的各个部分,也用它的iterator迭代路径中的各个部分;path构造目录结构的时候使用“/”运算符,非常直观。
比如path p1;
path p2 = p1/"something"; p1 /= "xxx.xxx";
2. filesystem名字空间一下有一些全局的函数,比如exists可以判断path是不是存在,is_directory函数判断是不是目录,file_size获得大小--该大小是一个夸平台的类型,可以表示32位或者64的大小;
其他is方法还有:
is_empty
is_other
is_regular_file
is_symlink
3. 最方便的一个功能是遍历path里的所有内容。directory_iterator。
path p;directory_iterator(p)就是迭代器的起点,无参数的directory_iterator()就是迭代器的终点。
还可以递归迭代,把上面的directory_iterator换成recursive_directory_iterator即可。
4. 创建目录。这里特别要提到一个方法是bool create_directories(const path& p); 如果p是一个目录(也就是is_diretory返回true)。它会递归的创建整个目录结构,免去自己一个一个创建的烦恼了。
其他创建方法还有:
create_directories
create_directory
create_hard_link
create_symlink
5. 还可以复制目录
copy_directory
copy_file
copy_symlink
6. 删除remove 递归删除remove_all
7. 改名字rename
8. 如果包含了<boost/filesystem/fstream.hpp>的话,还可以让fstream接受path作为参数。
下面上自己的代码(备忘):
#include <iostream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
using namespace std;
namespace fs = boost::filesystem ;
void getallfilename( string pathname , vector<string>& savename )
{
fs::path fullpath(pathname) ;
//判断目录是否存在
if( !fs::exists(fullpath) ) {
cout << "No thus path " << endl ;
return ;
}
//判断是否是目录
if( !fs::is_directory(fullpath) ) {
cout << "Is not a direcotry " << endl ;
return ;
}
// 利用fs::directory_iterator遍历path的内容
//end_iter默认指向path的末尾
fs::directory_iterator end_iter ;
for( fs::directory_iterator file_iter( fullpath ) ; file_iter != end_iter ; ++file_iter ) {
//判断结尾是否为".json"
if( fs::extension(*file_iter) == ".json" ) {
//将fs::path;类型转换成string类型
savename.push_back( fs::system_complete(*file_iter).leaf().string() ) ;
}
}
}
int main()
{
string path( "/usr/Resources/scene" ) ;
vector<string> savename ;
//获取指定目录下的所有json文件名,存入savename中
getallfilename( path , savename ) ;
vector<string>::iterator it = savename.begin() ;
for( ; it != savename.end() ; ++it ) {
cout << *it << endl ;
}
return 0;
}
注:
编译boost::filesystem库时会报错,因为先编译boost_system ,然后编译boost_filesystem ,所以编译时可以在编译器项目设置里面的Linker options中添加如下选项:
-lboost_system -lboost_filesystem