filesystem库——C++文件操作(输出文件名,判断文件是否为空、重命名、删除文件)

7 篇文章 0 订阅

头文件:#include <filesystem>
命令空间:using namespace std::filesystem;

由路径输出文件名

  • 输出路径中的文件名,即最后一位的
    字符串中的路径要是"D:\\1_wangyingjie\\code\\qwe.txt"或者"D:/1_wangyingjie/code/qwe.txt"
    std::string path = "D:/1_wangyingjie/code/qwe.txt";
    // std::filesystem库来获取给定路径的文件名。
    // std::filesystem::path是一个表示文件路径的类,它可以从给定的路径字符串构造而成
    std::filesystem::path file_name(path);
    //调用file_name对象的filename()成员函数来获取文件名部分,最后通过调用string()函数将文件名转换为std::string类型。
    std::string path1 = file_name.filename().string();
    std::cout << path1 << std::endl;
		
		输出结果:qwe.txt

由路径判断文件是否存在

#include <filesystem>
//判断文件是否存在
int main()
{
	std::string path = "./taichi.png";
	std::filesystem::path file_0(path);
	if (std::filesystem::exists(file_0))
	{
		cout << "存在" << endl;
	}
	else
	{
		cout << "不存在" << endl;

	}
}

文件重命名

在这里插入代码片

删除文件

string fi_path = "./data/a.txt";
std::filesystem::remove(std::filesystem::path(fi_path));

文件扩展名

namespace fs = std::filesystem;
std::string path = "./taichi.png";
std::filesystem::path file_0(path);
std::string filePath = path .path().string();
// 获取文件后缀名
std::string fileExtension = std::filesystem::path(filePath).extension().string();
 

递归的获取文件夹下的所有文件,并获取文件的修改时间


		std::string file_path = "./data/"
    std::string latest_file_path;
    for (auto& entry : std::filesystem::recursive_directory_iterator(file_path))
    {
    		// 如何非普通文件就跳过
        if (!std::filesystem::is_regular_file(entry.status()))
        {
            continue;
        }
        //如果不是file_path 就是当前的目录
        auto file_path = entry.path().string();
        // 得到文件的最后修改时间
				std::filesystem::file_time_type file_time = std::filesystem::last_write_time(entry);
				
    }

判断目录是否存在,若不存在创建

#include <iostream>
#include <filesystem>

bool CreateDirectoryIfNotExists(const std::string& directoryPath) 
{
    std::filesystem::path path(directoryPath);

    if (!std::filesystem::exists(path)) 
    {
        try 
        {
            std::filesystem::create_directories(path);
            return true; // 创建目录成功
        } 
        catch (const std::filesystem::filesystem_error& ex) 
        {
            std::cerr << "Error creating directory: " << ex.what() << std::endl;
            return false; // 创建目录失败
        }
    } else 
    {
        return true; // 目录已存在
    }
}

int main() {
    std::string outputDirectory = "path/to/your/directory";
    
    if (CreateDirectoryIfNotExists(outputDirectory)) {
        std::cout << "Directory created or already exists: " << outputDirectory << std::endl;
    } else {
        std::cerr << "Failed to create directory: " << outputDirectory << std::endl;
    }

    return 0;
}

得到一个文件的父目录

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
    // 你要获取父目录的文件的路径
    std::string filePath = "C:/example/somefile.txt";
    // 使用std::filesystem获取父目录
    std::filesystem::path parentPath = std::filesystem::path(filePath).parent_path();
    // 输出父目录的路径
    std::cout << "Parent directory: " << parentPath.string() << std::endl;

    return 0;
}

得到文件名称,文件名称不要后缀

要获取文件名称但不包括后缀,你可以使用stem()函数。stem()函数返回路径中文件名的部分,但不包括扩展名(后缀)。以下是如何使用stem()函数来获取文件名称但不包括后缀:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::string inputFile = "path/to/your/file.txt"; // 替换为你的文件路径

    // 获取文件名但不包括后缀
    std::string inputFileName = std::filesystem::path(inputFile).filename().stem().string();
    // 获取文件扩展名
    std::string fileExtension = std::filesystem::path(inputFile).extension().string();
    std::cout << "File name without extension: " << inputFileNameWithoutExtension << std::endl;

    return 0;
}

判断文件或目录是否存在

  1. 判断文件是否存在
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::string filePath = "path/to/your/file.txt";

    if (std::filesystem::exists(filePath) && std::filesystem::is_regular_file(filePath)) 
	{
        std::cout << "File exists." << std::endl;
    } else {
        std::cout << "File does not exist or is not a regular file." << std::endl;
    }

    return 0;
}

std::filesystem::exists函数用于检查指定路径的文件或目录是否存在。std::filesystem::is_regular_file函数用于检查文件是否为普通文件

  1. 判断目录是否存在
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::string directoryPath = "path/to/your/directory";

    if (std::filesystem::exists(directoryPath) && std::filesystem::is_directory(directoryPath)) 
	{
        std::cout << "Directory exists." << std::endl;
    } else {
        std::cout << "Directory does not exist or is not a directory." << std::endl;
    }

    return 0;
}

std::filesystem::exists函数用于检查指定路径的文件或目录是否存在
std::filesystem::is_directory函数则用于检查路径是否为目录

判断是文件还是目录

#include <filesystem>
#include <iostream>

int main() {
    std::filesystem::path outputDir = "/path/to/your/directory";
    std::string filename = "example.txt";

    std::filesystem::path one_file = outputDir.append(filename);

    if (std::filesystem::is_directory(one_file)) {
        std::cout << one_file << " is a directory." << std::endl;
    } else if (std::filesystem::is_regular_file(one_file)) {
        std::cout << one_file << " is a regular file." << std::endl;
    } else {
        std::cout << one_file << " is neither a directory nor a regular file." << std::endl;
    }

    return 0;
}

创建单个目录, 递归创建目录

1.create_directory

1.用于创建单个目录。
2.如果目录已存在,或者无法创建目录(例如由于权限问题),它将引发 std::filesystem::filesystem_error 异常。

#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path directoryPath = "/path/to/your/directory";

    try {
        std::filesystem::create_directory(directoryPath);
        std::cout << "Directory created successfully: " << directoryPath << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error creating directory: " << e.what() << std::endl;
    }

    return 0;
}

2. create_directories

1.用于递归创建目录路径中的所有目录,包括中间缺失的目录。
2.如果目录已存在,它什么也不做,不引发异常。
3. 如果某个目录无法创建(例如由于权限问题),它将继续尝试创建其余的目录,而不会中止整个过程。

#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::filesystem::path directoryPath = "/path/to/your/directory";

    try {
        std::filesystem::create_directories(directoryPath);
        std::cout << "Directories created successfully: " << directoryPath << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error creating directories: " << e.what() << std::endl;
    }

    return 0;
}

相对路径

获取一个路径相对于另一个路径的相对路径

std::string root = "/data/compress\\compress_dir\\file2\\1.txt" ;
std::string dirPrefix= "/data/compress" ;
std::filesystem::path rel(root );
std::filesystem::path fiter(dirPrefix);

// 求fiter相对于rel的相对路径
std::filesystem::path relative_path = std::filesystem::relative(fiter, rel);
// relative_path = L"compress_dir\\file2\\1.txt"

获取指定目录下的所有目录名称

/// <summary>
/// 获取指定目录下所有的目录名称
/// </summary>
/// <param name="directory_path"></param>
/// <returns></returns>
std::vector<std::string> get_subdirectories(const std::string& directory_path)
{
    std::vector<std::string> subdirectories;

    // 检查目录是否存在
    if (std::filesystem::exists(directory_path) && std::filesystem::is_directory(directory_path))
    {
        // 遍历目录下的所有条目
        for (const auto& entry : std::filesystem::directory_iterator(directory_path))
        {
            // 检查是否为目录
            if (std::filesystem::is_directory(entry.status()))
            {
                // 获取目录名称并添加到结果向量中
                subdirectories.push_back(entry.path().filename().string());
            }
        }
    }
    else
    {
        std::cout << "指定目录不存在或不是一个目录。" << std::endl;
    }

    return subdirectories;
}

统计给定目录下的文件数量

int count_files(const std::string& directory_path)
{
    int file_count = 0;

    // 检查目录是否存在
    if (std::filesystem::exists(directory_path) && std::filesystem::is_directory(directory_path))
    {
        // 遍历目录下的所有条目
        for (const auto& entry : std::filesystem::directory_iterator(directory_path))
        {
            // 检查是否为文件
            if (std::filesystem::is_regular_file(entry.status()))
            {
                ++file_count;
            }
        }
    }
    else
    {
        std::cout << "指定目录不存在或不是一个目录。" << std::endl;
    }
    return file_count;
}

获取指定目录下所有文件的绝对路径

std::vector<std::string> get_all_file_path(const std::string& directory_path) 
{
    std::vector<std::string> file_paths;
    for (const auto& entry : std::filesystem::recursive_directory_iterator(directory_path))
    {
        if (std::filesystem::is_regular_file(entry.path())) 
        {
            file_paths.push_back(entry.path().string());
        }
    }
    return file_paths;
}

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值