C++以扩展名提取文件夹中的文件名称并写入.txt中

 一、简介

利用扩展名提取文件名称在很多情况下能够方便我们对大规模数据进行分析。

本文以“.JPG”扩展名为例,通过C++代码实现。

二、完整代码

#include <iostream>
#include <fstream>
#include <experimental/filesystem>
#include <vector>
#include <string>

namespace fs = std::experimental::filesystem;

// 函数声明
std::vector<std::string> getJpgFiles(const std::string& folderPath);

int main() {
	std::string folderPath = " your path"; // 替换为你的文件夹路径

	std::vector<std::string> jpgFiles = getJpgFiles(folderPath);

	// 构建输出文件路径
	std::string outputPath = folderPath + "/name.txt";

	// 打开输出文件
	std::ofstream outputFile(outputPath);

	if (!outputFile.is_open()) {
		std::cerr << "Error opening " << outputPath << std::endl;
		return 1;
	}

	// 将文件名写入输出文件
	for (const auto& jpgFile : jpgFiles) {
		outputFile << jpgFile << std::endl;
	}

	// 关闭输出文件
	outputFile.close();

	std::cout << "JPG files in the folder are saved in " << outputPath << "." << std::endl;

	return 0;
}

// 实现函数,返回文件夹中以“.JPG”为扩展名的文件名称列表
std::vector<std::string> getJpgFiles(const std::string& folderPath) {
	std::vector<std::string> jpgFiles;

	try {
		for (const auto& entry : fs::directory_iterator(folderPath)) {
			fs::file_status status = entry.status();
			if (fs::is_regular_file(status) && entry.path().extension() == ".JPG") {
				jpgFiles.push_back(entry.path().filename().string());
			}
		}
	}
	catch (const fs::filesystem_error& e) {
		std::cerr << "Error accessing the folder: " << e.what() << std::endl;
	}

	return jpgFiles;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值