• C++ Boost 文件系统相关函数


    基础处理

    #include <iostream>
    #include <boost/foreach.hpp>
    #include <boost/filesystem.hpp>
    
    using namespace std;
    using namespace boost;
    using namespace boost::filesystem;
    
    int main(int argc, char *argv[])
    {
    	// 判断路径是否为空
    	filesystem::path path_a;
    	if (path_a.empty())
    		cout << "文件路径为空" << endl;
    
    	// 提取区间字符
    	char str[] = "hello / lyshark";
    	filesystem::path path_b(str + 6, str + 7);
    	cout << "区间提取: " << path_b << endl;
    
    	// 追加字符串序列
    	path_b /= "etc";
    	string filename_a = "xinetd.conf";
    	path_b.append(filename_a.begin(), filename_a.end());
    	cout << "追加后的字符串: " << path_b << endl;
    
    	// 追加字符串concat
    	filesystem::path path_c(str + 6, str + 7);
    	string filename_b = "lyshark.log";
    	path_c += "etc";
    	path_c.concat(filename_b.begin(), filename_b.end());
    	cout << "追加后的字符串: " << path_c << endl;
    
    	// 路径切割函数
    	filesystem::path path_d("/usr/loca/include/lyshark.hpp");
    	cout << "原始路径: " << path_d.string() << endl;
    	cout << "返回主路径: " << path_d.parent_path() << endl;
    	cout << "返回主文件名: " << path_d.stem() << endl;
    	cout << "返回全文件名: " << path_d.filename() << endl;
    	cout << "返回扩展名: " << path_d.extension() << endl;
    
    	// 返回绝对相对路径
    	filesystem::path path_e("c://windows/lyshark.hpp");
    	cout << "是否为绝对路径: " << path_e.is_absolute() << endl;
    	cout << "返回根分区盘符: " << path_e.root_name() << endl;
    	cout << "返回根路径: " << path_e.root_directory() << endl;
    	cout << "返回分区绝对盘符: " << path_e.root_path() << endl;
    	cout << "返回相对路径: " << path_e.relative_path() << endl;
    
    	cout << "只保留路径: " << path_e.replace_extension() << endl;
    	cout << "修改后缀扩展: " << path_e.replace_extension("jsp") << endl;
    
    	// 字符路径分割
    	filesystem::path path_f("c://windows/system32/etc/lyshark.cpp");
    	BOOST_FOREACH(auto& x, path_f)
    	{
    		cout << x << endl;
    	}
    
    	getchar();
    	return 0;
    }
    

    文件属性操作:

    #include <iostream>
    #include <fstream>
    
    #include <boost/optional.hpp>
    #include <boost/filesystem.hpp>
    
    using namespace std;
    using namespace boost;
    using namespace boost::filesystem;
    
    int main(int argc, char *argv[])
    {
    	namespace fs = boost::filesystem;
    
    	// 获取文件大小
    	fs::path ptr("c://lyshark.exe");
    	try
    	{
    		cout << "文件大小: " << fs::file_size(ptr) / 1024 << " KB" << endl;
    	}
    	catch (filesystem_error& e)
    	{
    		cout << "异常: " << e.path1() << e.what() << endl;
    	}
    
    	// 获取修改时间
    	std::time_t timer = filesystem::last_write_time(ptr);
    	cout << "(修改时间)时间戳: " << timer << endl;
    
    	// 获取盘符容量
    	space_info size = filesystem::space("c://");
    	cout << "总容量: " << size.capacity / 1024 / 1024 << " MB" << endl;
    	cout << "剩余容量: " << size.free / 1024 / 1024 << " MB" << endl;
    	cout << "可用容量: " << (size.capacity - size.free) / 1024 / 1024 << " MB" << endl;
    
    	// 文件与目录判断
    	filesystem::path root = "c://lyshark.exe";
    	cout << "是否为目录: " << is_directory(root) << endl;
    	cout << "是否存在: " << exists(root) << endl;
    
    	// 文件状态与权限检测
    	filesystem::path root_type = "c://lyshark.exe";
    	cout << "类型检测: " << filesystem::status(root_type).type() << endl;
    	cout << "权限检测: " << filesystem::status(root_type).permissions() << endl;
    
    	getchar();
    	return 0;
    }
    

    文件操作:

    #include <iostream>
    #include <fstream>
    #include <boost/filesystem.hpp>
    
    using namespace std;
    using namespace boost;
    
    int main(int argc, char *argv[])
    {
    	namespace fs = boost::filesystem;
    
    	// 路径拼接
    	fs::path current_path = fs::current_path();
    	cout << "当前目录: " << current_path << endl;
    
    	fs::path init_path = fs::initial_path();
    	cout << "初始目录: " << init_path << endl;
    
    	fs::path file_path = current_path / "lyshark";
    	cout << "拼接后的路径: " << file_path << endl;
    
    	// 判断文件是否存在
    	filesystem::path p_tree = "c://a/abc.txt";
    	cout << "文件是否存在: " << filesystem::exists(p_tree) << endl;
    	cout << "文件是否为空: " << filesystem::is_empty(p_tree) << endl;
    
    	// 创建空目录
    	auto directory_ref = filesystem::create_directory(filesystem::path("c://11111"));
    	cout << "是否创建成功: " << directory_ref << endl;
    
    	// 创建递归目录
    	filesystem::path root_tree = filesystem::path("c://");
    	auto directorys_ref = filesystem::create_directories(root_tree / "sub_dir_a" / "sub_dir_b");
    	cout << "是否创建成功: " << directorys_ref << endl;
    
    	// 文件或目录拷贝命令
    	filesystem::copy_directory("c://lyshark", "d://lyshark");
    	filesystem::copy_file("c://lyshark.exe", "d://lyshark/lyshark.exe");
    
    	// 重命名文件或目录
    	filesystem::rename("c://lyshark.exe", "c://www.exe");
    
    	// 删除文件或目录
    	auto remove_ref = filesystem::remove("c://lyshark");
    	cout << "是否已删除(空目录): " << remove_ref << endl;
    	
    	auto remove_all_ref = filesystem::remove_all("c://lyshark");
    	cout << "是否已删除(非空目录): " << remove_all_ref << endl;
    
    	getchar();
    	return 0;
    }
    

    迭代目录: 针对特定目录的枚举操作,或过滤查找特定文件。

    #include <iostream>
    #include <string>
    #include <vector>
    #include <boost/foreach.hpp>
    #include <boost/filesystem.hpp>
    
    #include <boost/algorithm/string/replace.hpp>
    #include <boost/xpressive/xpressive.hpp>
    
    using namespace std;
    using namespace boost;
    using namespace boost::filesystem;
    using namespace boost::xpressive;
    
    // directory_iterator 不支持深层遍历,只能遍历一层
    void disk_foreach()
    {
        // 枚举当前路径下的所有目录
        directory_iterator end;
        for (directory_iterator pos("c://"); pos != end; ++pos)
        {
            cout << *pos << endl;
        }
    
        // 定义迭代器实现枚举目录
        typedef std::pair<directory_iterator, directory_iterator> dir_range;
        dir_range dir(directory_iterator("c://"), directory_iterator());   // 定义迭代起始与结束令
    
        BOOST_FOREACH(auto &x, dir)
        {
            cout << x << endl;
        }
    }
    
    // 遍历文件函数版
    void GetFilePath(const string& pathName, std::vector <std::string> &recusiveFileVec)
    {
    	boost::filesystem::recursive_directory_iterator rdi(pathName);
    	boost::filesystem::recursive_directory_iterator end_rdi;
    	recusiveFileVec.empty();
    
    	for (; rdi != end_rdi; rdi++)
    	{
    		if (is_directory(*rdi))
    		{
    			//std::cout << *rdi << "is pathName" << std::endl;
    		}
    		else
    		{
    			recusiveFileVec.push_back(rdi->path().string());
    			//std::cout << *rdi << " is a file" << std::endl;
    		}
    	}
    }
    
    // 递归迭代目录(低效率版)
    void recursive_dir(const path& dir)
    {
        directory_iterator end;
    
        for (directory_iterator pos(dir); pos != end; ++pos)
        {
            // 判断是否为目录
            if (is_directory(*pos))
            {
                recursive_dir(*pos);
            }
            else
            {
                cout << *pos << endl;
            }
        }
    }
    
    // 递归目录(高效版)
    void recursive_dir_new(const path& dir)
    {
        // level() 返回当前目录深度
        recursive_directory_iterator end;
        for (recursive_directory_iterator pos(dir); pos != end; ++pos)
        {
            // 只输出只有一层的路径
            if (pos.level() == 0)
            {
                cout << "目录深度: " << pos.level() << " 路径: " << *pos << endl;
            }
        }
    }
    
    // 递归寻找文件(不支持正则处理)
    boost::optional<path> recursive_find_file(const path& dir, const string& filename)
    {
        // 定义返回值类型,这个optional返回容器
        typedef boost::optional<path> result_type;
    
        // 检测如果不是目录则直接退出
        if (!exists(dir) || !is_directory(dir))
        {
            return result_type();
        }
    
        recursive_directory_iterator end;
        for (recursive_directory_iterator pos(dir); pos != end; ++pos)
        {
            // 如果不是目录并且文件名相同则返回这个路径
            if (!is_directory(*pos) && pos->path().filename() == filename)
            {
                return result_type(pos->path());
            }
        }
        return result_type();
    }
    
    // 递归寻找文件(支持正则处理)
    std::vector<path> recursive_find_file_regx(const path& dir, const string& filename)
    {
        // 定义正则表达式静态对象
        static boost::xpressive::sregex_compiler rc;
    
        // 先判断正则对象是否正常
        if (!rc[filename].regex_id())
        {
            // 处理文件名 将.替换为\. 将 * 替换为 .*
            std::string str = replace_all_copy(replace_all_copy(filename, ".", "\."), "*", ".*");
            rc[filename] = rc.compile(str);     // 创建正则
        }
    
        typedef std::vector<path> result_type;
        result_type vct;
        if (!exists(dir) || !is_directory(dir))
        {
            return vct;
        }
    
        recursive_directory_iterator end;
        for (recursive_directory_iterator pos(dir); pos != end; ++pos)
        {
            if (!is_directory(*pos) && regex_match(pos->path().filename().string(), rc[filename]))
            {
                // 如果找到了就加入到vector里面
                vct.push_back(pos->path());
            }
        }
        return vct;
    }
    
    // 文件复制操作函数
    size_t my_copy_file(const path& from_dir, const path& to_dir, const string& filename = "*")
    {
        // 判断源文件路径必须为目录
        if (!is_directory(from_dir))
        {
            cout << "原始文件不能为文件" << endl;
            return 0;
        }
    
        // 查找原目录下的所有文件
        auto vec = recursive_find_file_regx(from_dir, filename);
        if (vec.empty())
        {
            cout << "目录中没有文件,自动跳过拷贝" << endl;
            return 0;
        }
    
        path path_ptr;
        for (auto& ptr : vec)
        {
            // 拆分基本路径与目标路径
            path_ptr = to_dir / ptr.string().substr(from_dir.string().length());
            
            // 判断并创建子目录
            if (!exists(path_ptr.parent_path()))
            {
                create_directories(path_ptr.parent_path());
            }
            cout << "源文件: " << path_ptr.string() << " 拷贝到: " << to_dir.string() << endl;
            
            // 开始拷贝文件
            boost::filesystem::copy_file(ptr, path_ptr);
        }
        cout << "拷贝总文件数: " << vec.size() << endl;
        return vec.size();
    }
    
    int main(int argc, char *argv[])
    {
        // 不使用通配符寻找
        auto ref = recursive_find_file("c:\lyshark", "123.txt");
        if (ref)
            cout << "找到文件: " << *ref << endl;
    
        // 使用通配符寻找
        auto  regx_ref = recursive_find_file_regx("c:\lyshark", "*.txt");
    
        cout << "找到文件: " << regx_ref.size() << endl;
        for (boost::filesystem::path &ptr : regx_ref)
        {
            cout << "找到文件路径: " << ptr << endl;
        }
    
        // 输出枚举内容
    	std::vector <std::string> file_path;
    
    	GetFilePath("C://backup", file_path);
    	for (int x = 0; x < file_path.size(); x++)
    	{
    		std::cout << file_path[x] << std::endl;
    	}
    
        // 实现文件拷贝
        my_copy_file("c:\lyshark", "c:\c");
    
        getchar();
        return 0;
    }
    

    文件流操作:

    #include <iostream>
    #include <fstream>
    
    #include <boost/filesystem.hpp>
    #include <boost/filesystem/fstream.hpp>
    
    using namespace std;
    using namespace boost;
    
    
    void get_file_in_path()
    {
    	namespace fs = boost::filesystem;
    
    	filesystem::path p("c://a/abc.txt");
    	fs::ifstream ifs(p);
    
    	if (ifs.is_open() == 1)
    	{
    		cout << ifs.rdbuf() << endl;
    	}
    }
    
    int main(int argc, char *argv[])
    {
    	namespace fs = boost::filesystem;
    
    	// 路径拼接
    	fs::path current_path = fs::current_path();
    	cout << "当前目录: " << current_path << endl;
    
    	fs::path file_path = current_path / "lyshark";
    	cout << "拼接后的路径: " << file_path << endl;
    	getchar();
    	return 0;
    }
    

    版权声明: 本博客,文章与代码均为学习时整理的笔记,博客中除去明确标注有参考文献的文章,其他文章【均为原创】作品,转载请务必【添加出处】,您添加出处是我创作的动力!
    如果您恶意转载本人文章,则您的整站文章,将会变为我的原创作品!
  • 相关阅读:
    printf函数实现的深入剖析
    rhel/centos播放mp3文件
    GRUB(GRand Unified Boot loader)引导加载程序
    NAT DHCP WWW rc.local
    论文 毕业设计 相关 用语 评语
    Linux禁止单用户模式(single)来增强系统安全
    Kernel command using Linux system calls
    GNU-ld链接脚本浅析
    AT&T汇编心得之间接寻址和LEA指令
    Linux 汇编语言开发指南
  • 原文地址:https://www.cnblogs.com/LyShark/p/14519757.html
Copyright © 2020-2023  润新知