C++11 学习笔记(7) —— path, wpath

来源:互联网 发布:mac词典发音 编辑:程序博客网 时间:2024/04/30 06:42

1. 简介

    使用C++编程,经常涉及到对文件的相关操作,例如,判断文件是否存在、获取文件所在的路径名、遍历某个目录下的所有文件、创建新的目录等。在旧风格的C++编程中,一般通过操作系统提供的API、字符串操作等实现上述功能。

    C++11 提供的<filesystem> 头文件提供了丰富的文件操作的类和函数。filesystem 库是一个可一直的文件系统操作相关的库,使用POSIX标准表示文件系统的路径,支持多种操作系统平台,因此使用filesystem可以编写跨平台操作目录,文件的C++程序。本文对<filesystem>常用的path 和 wpath 作个简单的介绍。

2. path

    在<filesystem>中,最常用的应该是basic_path 模板类。该类提供了对路径的相关操作,其定义如下所示:

template<class String, class Traits>class basic_path;
    在实际使用中,我们经常会使用 path 或 wpath 而不是 basic_path,前两者是对basic_path的类型的定义

typedef basic_path<string, path_traits> path;typedef basic_path<wstring, wpath_traits> wpath;

很明显的可以看出,path用于string的操作,而 wpath用于处理 wstring 路径。常用的操作如示例代码所示:

#include "stdafx.h"#include<filesystem>#include<iostream>using namespace std;using namespace std::tr2::sys;  //<filesystem>的命名空间int _tmain(int argc, _TCHAR* argv[]){//定义一个 path 对象path p("D:\\Test\\abc.cpp");// 系统全路径cout << "system_complete: " << system_complete(p) <<endl;// 将 Path 转换成字符串显示cout << "string: " << p.string() << endl;// 所在目录的字符串形式cout << "directory_string: " << p.directory_string() << endl;//父目录cout << "parent_path: " << p.parent_path() << endl;// 不含扩展名的全路径名cout << "stem: " << p.stem() << endl;// 文件名cout << "filename: " << p.filename() << endl;// 文件后缀cout << "extension: " << p.extension() << endl;// 根目录名称cout << "root_name: " << p.root_name() << endl;// 根目录路径cout << "root_path: " << p.root_path() << endl;// 替换后缀为空cout << "replace_extension: " << p.replace_extension() << endl;// 将后缀替换为指定字符串cout << "replace_extension(txt): " << p.replace_extension("txt") << endl;// 删除文件名cout << "remove_filename: " << p.remove_filename() << endl;system("pause");return 0;}

输出结果如下图所示

上例仅给出对path对象常用的一些操作,该类提供了对路径的各种操作,避免了我们自己实现路径的转换,文件名的提取等常用操作。


使用path/wpath 可以很方便的实现对路径的管理和操作,在新写的代码中,不防体验一下。


原创粉丝点击