C++文件系统

本文介绍了C++标准库filesystem的使用,包括创建和删除目录、获取文件状态、遍历文件系统等核心功能。通过示例代码详细展示了如何进行单层和多级目录创建、文件夹删除、文件最后修改时间获取以及遍历指定路径下的文件和子目录。同时,还讲解了path类的方法,如current_path、root_directory等,以及file_status类用于判断文件类型的用法。
摘要由CSDN通过智能技术生成

filesystem简介

#include <filesystem>
#include <iostream>
using namespace std;

int main()
{
	filesystem::path ur1("fileBox");
	if (!filesystem::exists(ur1))
	{
		cout << "不存在" << endl;
	}//路径存在不做创建处理
	filesystem::create_directory("fileBox");
	//如果目录下没有就创建一个叫fileBox的文件夹,单层目录
	filesystem::create_directories("a/b/c");//创建多级目录
	filesystem::remove_all(ur1);//删除整个文件夹
	auto time = filesystem::last_write_time("a/b/c");//得到c最后一次写的时间
	cout << time.time_since_epoch() << endl;
	return 0;
}

在官方文档还有好多

path类

 filesystem::path ur1("fileBox");
	filesystem::path curUAL = filesystem::current_path();
	cout << curUAL.string() << endl;//输出当前文件路径
	cout << curUAL.root_directory() << endl;//根目录
	cout << curUAL.relative_path() << endl;//相对路径
	cout << curUAL.root_name() << endl;//根名
	cout << curUAL.root_path() << endl;//根路径

file_statues类

文件状态判断:

void test_file_statues(filesystem::file_status a)
{
	switch (a.type())
	{
	case filesystem::file_type::regular:
		cout << "磁盘文件" << endl;
		break;
	case filesystem::file_type::directory:
		cout << "目录文件" << endl;
		break;
	case filesystem::file_type::not_found:
		cout << "目录不存在" << endl;
		break;
	case filesystem::file_type::none:
		cout << "不清楚" << endl;
	}
}


 filesystem::create_directory("file");
	 test_file_statues(filesystem::status("file"));

遍历文件操作

void traverDirectory()
{
	filesystem::path ur1("C:\\Users");
	if (!filesystem::exists(ur1))
		cout << "路径不存在" << endl;
	filesystem::directory_entry input(ur1);
	if (input.status().type() != filesystem::file_type::directory)
		cout << "ur1不是目录" << endl;
	filesystem::directory_iterator dir(ur1);
	for (auto v : dir)
		cout << v.path().filename() << endl;

}
//遍历当前文件夹下的所有文件
void traverDirectoryAllfile()
{
	filesystem::path ur1("C:\\");
	if (!filesystem::exists(ur1))
		cout << "路径不存在" << endl;
	set<string> dirset;
	filesystem::directory_iterator begin(ur1);
	for (filesystem::directory_iterator end, begin(ur1); begin != end; ++begin)
	{
		if (!filesystem::is_directory(begin->path()))
		{
			dirset.insert(begin->path().filename().string());
		}
	}
	for (auto v : dirset)
	{
		cout << v << endl;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值