要点:
1 头文件
#include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations
#include <iostream> // for std::cout
using boost::filesystem;
2 在path.hpp中定义了路径类
a 支持多种编码格式,包括unicode
b 多种构造函数,可支持多种类型的构造
c 支持多种路径格式的写法,如‘\’与'/'的路径分隔符问题
d 支持多种访问函数,可参考path类源码
总之,一句话,该类真的很方便,很强大;
3 在operations.hpp文件中定义了很多关于访问,操纵文件的一些实用函数
如; std::cout<<argv[0]<< " " << file_size(argv[0])<< endl;
path p (argv[0]);
exists(p);
is_regular_file(p);
is_directory(p);
等等,在使用的时候,打开头文件查询便知;
4 directory_iterator提供了目录的迭代器功能,如:
path pt (argv[0]);
path p = pt.parent_path();
copy(directory_iterator(p), directory_iterator(), ostream_iterator<directory_entry>(cout, "\n"));//输出当前运行目录中的文件及目录
directory_entry
里面记录了路径及status信息,代表迭代的对象;
并且与标准库兼容,如:
typedef vector<path> vec; // store paths,
vec v; // so we can sort them later
copy(directory_iterator(p), directory_iterator(), back_inserter(v));
sort(v.begin(), v.end());
for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it)
{
cout << " " << *it << '\n';
}
5 path的例子,看例子学习,一切尽在不言中!
for (; argc > 1; --argc, ++argv)
p /= argv[1];//利用operator/来
cout << "\ncomposed path:\n";
cout << " cout << -------------: " << p << "\n";
cout << " make_preferred()----------: " << path(p).make_preferred() << "\n";
cout << "\nelements:\n";
for (path::iterator it(p.begin()), it_end(p.end()); it != it_end; ++it)
cout << " " << *it << '\n';
cout << "\nobservers, native format:" << endl;
# ifdef BOOST_POSIX_API
cout << " native()-------------: " << p.native() << endl;
cout << " c_str()--------------: " << p.c_str() << endl;
# else // BOOST_WINDOWS_API
wcout << L" native()-------------: " << p.native() << endl;
wcout << L" c_str()--------------: " << p.c_str() << endl;
# endif
cout << " string()-------------: " << p.string() << endl;
wcout << L" wstring()------------: " << p.wstring() << endl;
cout << "\nobservers, generic format:\n";
cout << " generic_string()-----: " << p.generic_string() << endl;
wcout << L" generic_wstring()----: " << p.generic_wstring() << endl;
cout << "\ndecomposition:\n";
cout << " root_name()----------: " << p.root_name() << '\n';
cout << " root_directory()-----: " << p.root_directory() << '\n';
cout << " root_path()----------: " << p.root_path() << '\n';
cout << " relative_path()------: " << p.relative_path() << '\n';
cout << " parent_path()--------: " << p.parent_path() << '\n';
cout << " filename()-----------: " << p.filename() << '\n';
cout << " stem()---------------: " << p.stem() << '\n';
cout << " extension()----------: " << p.extension() << '\n';
6 file stream
从标准库的file stream中继承实现boost的类,增加以path作为函数参数的函数;
总结,本文仅简单的介绍了boost库的Filesystem库的基本使用方法,更详细的使用请参考源码和相关文档;该库在实际当中是非常有用的;