一、简介
利用扩展名提取文件名称在很多情况下能够方便我们对大规模数据进行分析。
本文以“.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;
}