Windows中获取某个目录下的所有文件名(C++)

Introduction

在Windows系统下获取某个目录下的所有文件名有多种方法,比如:利用Windows自带的函数(包含#include <Windows.h>),利用boost库,利用C++的新特性。
这里利用C++14/17中的文件管理系统filesystem来获取某个目录下的所有文件名,这种方法十分简单,几行代码轻松搞定。
如果编译器支持C++17,将下列代码

// C++14
#include <experimental/filesystem>  
namespace fs = std::experimental::filesystem;

改为

// c++17
#include <filesystem>
namespace fs = std::filesystem; 

Code

以下是完整代码,将生成的exe文件放入需要读取文件名的路径下,运行exe即可。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <experimental/filesystem>  //C++14
namespace fs = std::experimental::filesystem;

void getFileNames(const std::string dir, std::vector<std::string>& vFileNames, bool extension = 1)
{
	for (const auto & entry : fs::directory_iterator(dir))
	{
		if (1 == extension)
		{
			// with extension
			vFileNames.push_back(entry.path().filename().string());
		}
		else if (0 == extension)
		{
			// without extension
			std::string fileName;
			fileName = entry.path().filename().string();
			int pos = fileName.rfind(".");
			vFileNames.push_back(std::string(fileName, 0, pos));
			fileName.clear();
		}
	}
}


int main(int argc, char* argv[])
{
	// get current directory
	std::string argv_str(argv[0]);
	std::string dir = argv_str.substr(0, argv_str.find_last_of("\\"));

	// get current execute's name
	std::string exeName1 = argv_str.substr(argv_str.find_last_of("\\") + 1);
	std::string exeName0 = exeName1.substr(0, exeName1.find_last_of("."));

	std::cout << "current path is " << dir << std::endl;
	std::cout << "output files' name with extension or not?" << std::endl;
	std::cout << "1: with extension" << std::endl;
	std::cout << "0: without extension" << std::endl;

	// with extension or not
	bool sign = 1;
	std::cin >> sign;
	std::cout << std::endl;

	// delete execute's name
	std::vector<std::string> vFileNames;
	getFileNames(dir, vFileNames, sign);
	std::string exeName = (sign == 1 ? exeName1 : exeName0);
	std::vector<std::string>::const_iterator iter = 
	std::find(vFileNames.begin(), vFileNames.end(), exeName);
	vFileNames.erase(iter);
	
	// show and output all file's name
	std::ofstream ofile(dir + "//fileName.txt");
	for (std::string fileName : vFileNames)
	{
		std::cout << fileName << std::endl;
		ofile << fileName << std::endl;
	}
	ofile.close();
		
	system("pause");
    return 0;
}

Reference

How can I get the list of files in a directory using C or C++?
HOW TO LIST THE FILES IN A DIRECTORY IN C++

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值