Visual Studio 2015 编译与使用Boost库进行文件与目录的操作

版权声明:转载请注明出版 https://blog.csdn.net/matt45m/article/details/89007235

前言

1.Boost库是一个功能非常强大的跨平台开源C++库,我这里只演示如何在win7下visual studio 2015里做boost库的boost::filesystem来操作文件、目录。
2.我的环境是windows 7 64位,visual studio 2015,所用的boost库是boost_1_66_0-msvc-11.0-64.exe,boost的各个版本可以从这里下载,我用的版本csdn的下载地址:https://download.csdn.net/download/matt45m/11090742。

一、安装与配置Boost库

1.下载boost库之后开始安装,更改自己想要安装在的路径。
在这里插入图片描述
安装之后的目录如下:
在这里插入图片描述
2.新建一个项目vs2015的C++项目,选自己存放项目的路径。
(1)新建一个项目。
在这里插入图片描述
(2)选择项目类型,输入项目名,点确定。
在这里插入图片描述
(3)从视图调出属性窗口。
在这里插入图片描述
2.开始配置boost的相关路径。
(1)点属性管理器,打开属性对话框,我这里配置的是 Debug 64位。
在这里插入图片描述
(2)设置相VC++目录,包含的目录与库目录,看着自己的环境配置这两个目录。
在这里插入图片描述
(3)链接器的路径配置,确定,配置完成。
在这里插入图片描述

二、使用boost库操作文件与目录

1.在当前项目中添加一个源文件,引入文件相关的头文件和定义一个名字空间。

#include<boost/filesystem.hpp>
//定义一个boost库的命名空间
namespace fs = boost::filesystem;

2.文件操作代码演示
(1)全局函数判断当前路径。

	//初始化一个路径
	string dir_path = "F:/train_faces/";
	//判断传入路径是否存在
	if (fs::exists(dir_path))
	{
		std::cout << "当前传入的目录存在!" << endl;
	}
	//判断传入的路径是否为目录
	if (fs::is_directory(dir_path))
	{
		std::cout << "当前传入的路径是目录" << endl;
	}
	//判断传入的目录是否为空
	if (!fs::is_empty(dir_path))
	{
		std::cout << "当前传入的目录不为空目录" << endl;
	}

(2)遍历当前目录下的子文件。

	//只遍历当前路径下第一层文件
	fs::directory_iterator begin_iter(dir_path);
	fs::directory_iterator end_iter;
	for(;begin_iter != end_iter; begin_iter++ )
	{
		string file_name = begin_iter->path().string();
		std::cout << file_name << endl;
	}

(3)递归遍历当前路径下所有子文件。

//递归遍历当前目录下的所有子文件
	fs::recursive_directory_iterator begin(dir_path);
	fs::recursive_directory_iterator end;
	for (; begin != end; begin++)
	{
		string file_name = begin->path().string();
		std::cout << file_name << endl;
	}

输出结果:
在这里插入图片描述
(3)文件相关的操作。

//初始化一个路径
	string dir_path = "F:/train_faces/01/1.pgm";
	boost::filesystem::path filePath(dir_path);

	//得到当前文件父目录("F:/train_faces/01/")
	cout << filePath.parent_path() << endl;  
	//得到当前文件名("1.pgm")
	cout << filePath.filename() << endl;  
	//得到当前文件名转为string("1.pgm")
	cout << filePath.filename().string() << endl;
	//得到当前文件名不包括扩展名("1")
	cout << filePath.stem() << endl; 
	//得到当前文件扩展名(".pgm")
	cout << filePath.extension() << endl; 

结语

1.boost是一个强大的C++库,文件操作只是其中的一小部分功能,如果要使用可以看官方的文档或者相关书箱。
2.关于boost库的使用,如果有兴趣的可以加群:487350510互相讨论学习。

猜你喜欢

转载自blog.csdn.net/matt45m/article/details/89007235
今日推荐