以下知识点转自:点击打开原文链接
今天拿起手要用C++写个小工具,从指定的目录递归遍历文件,然后做一下处理。又翻了一下boost的filesystem库。小结一下,希望能加深印象,免得下次又要查看文档。
1. path对象就是一个跨平台的路径对象。有许多方法访问路径的各个部分,也用它的iterator迭代路径中的各个部分;3. 最方便的一个功能是遍历path里的所有内容。directory_iterator。
path p;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
boost::filesystem库使用入门,布布扣,bubuko.com
原文:http://blog.csdn.net/hp_satan/article/details/36199839