boost::filesystem使用入门体验
boost::filesystem使用入门体验
最近开始看boost::filesystem的tutorial,并且进行了一些代码调试,将一些体会简单总结一下。
CMake的添加
find_package(Boost REQUIRED COMPONENTS filesystem)
target_link_libraries(${PROJECT_NAME} boost_filesystem boost_system)
注意:就算只使用boost_filesystem,也要在后面把boost_system添加上,否则,会在编译时出错:报错类型为
error: undefined reference to symbol '_ZN5boost6system15system_categoryEv
头文件和命名空间
一般情况下,头文件是:
#include <boost/filesystem.hpp>
命名空间是:
using namespace boost::filesystem;
或者是使用简写:
using namespace fs = boost::filesystem;
常用类和函数
file_size(路径名):返回文件大小
path p(路径名); 创建一个path对象,用路径名初始化
bool exists(path):文件/文件夹是否存在
bool is_directory(path):是否是一个文件夹
bool is_regular_file(path):是否是一个正常文件
directory_iterator:遍历目录所用的类,用path初始化
directory_entry:directory_iterator的值类型,常使用path()和filename()两个成员
下面是一段示例代码:
#include <iostream>
#include <boost/filesystem.hpp>
using std::cout;
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Usage: tut3 path\n";
return 1;
}
path p (argv[1]);
try
{
if (exists(p))
{
if (is_regular_file(p))
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p))
{
cout << p << " is a directory containing:\n";
for (directory_entry& x : directory_iterator(p))
cout << " " << x.path() << '\n';
}
else
cout << p << " exists, but is not a regular file or directory\n";
}
else
cout << p << " does not exist\n";
}
catch (const filesystem_error& ex)
{
cout << ex.what() << '\n';
}
return 0;
}
如果想要加入目录中文档的排序,应该这样些:
#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/filesystem.hpp>
using std::cout;
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Usage: tut4 path\n";
return 1;
}
path p (argv[1]);
try
{
if (exists(p))
{
if (is_regular_file(p))
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p))
{
cout << p << " is a directory containing:\n";
std::vector<path> v;
for (auto&& x : directory_iterator(p))
v.push_back(x.path());
std::sort(v.begin(), v.end());
for (auto&& x : v)
cout << " " << x.filename() << '\n';
}
else
cout << p << " exists, but is not a regular file or directory\n";
}
else
cout << p << " does not exist\n";
}
catch (const filesystem_error& ex)
{
cout << ex.what() << '\n';
}
return 0;
}
创建文件
boost::filesystem::ofstream file(path);
注意要加上头文件
#include <boost/filesystem/fstream.hpp>
以上,引用自:
https://www.boost.org/doc/libs/1_70_0/libs/filesystem/doc/tutorial.html