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

来源:互联网 发布:哪个云盘源码好用 编辑:程序博客网 时间:2024/05/16 05:50

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的类型的定义

[cpp] view plaincopy
  1. typedef basic_path<string, path_traits> path;  
  2. typedef basic_path<wstring, wpath_traits> wpath;  

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

[cpp] view plaincopy
  1. #include "stdafx.h"  
  2. #include<filesystem>  
  3. #include<iostream>  
  4.   
  5. using namespace std;  
  6. using namespace std::tr2::sys;  //<filesystem>的命名空间  
  7.   
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.     //定义一个 path 对象  
  11.     path p("D:\\Test\\abc.cpp");  
  12.   
  13.     // 系统全路径  
  14.     cout << "system_complete: " << system_complete(p) <<endl;  
  15.   
  16.     // 将 Path 转换成字符串显示  
  17.     cout << "string: " << p.string() << endl;  
  18.   
  19.     // 所在目录的字符串形式  
  20.     cout << "directory_string: " << p.directory_string() << endl;  
  21.   
  22.     //父目录  
  23.     cout << "parent_path: " << p.parent_path() << endl;  
  24.   
  25.     // 不含扩展名的全路径名  
  26.     cout << "stem: " << p.stem() << endl;  
  27.   
  28.     // 文件名  
  29.     cout << "filename: " << p.filename() << endl;  
  30.   
  31.     // 文件后缀  
  32.     cout << "extension: " << p.extension() << endl;  
  33.   
  34.     // 根目录名称  
  35.     cout << "root_name: " << p.root_name() << endl;  
  36.       
  37.     // 根目录路径  
  38.     cout << "root_path: " << p.root_path() << endl;  
  39.   
  40.     // 替换后缀为空  
  41.     cout << "replace_extension: " << p.replace_extension() << endl;  
  42.   
  43.     // 将后缀替换为指定字符串  
  44.     cout << "replace_extension(txt): " << p.replace_extension("txt") << endl;  
  45.   
  46.     // 删除文件名  
  47.     cout << "remove_filename: " << p.remove_filename() << endl;  
  48.   
  49.     system("pause");  
  50.     return 0;  
  51. }  

输出结果如下图所示

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


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

转载自http://blog.csdn.net/fire_lord/article/details/8582979

0 0
原创粉丝点击