C++ 获取文件夹下的全部文件及指定文件(代码)

1.(C++17)获得指定目录下的所有文件(不搜索子文件夹)

vs2017版本可以使用C++17,但也需要设置下项目属性:右击项目 -> 属性 -> 配置属性 -> C/C++ -> 常规 -> 语言 -> 编译器语言,然后将编译器语言改为C++17。

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
	// 指定要遍历的文件夹路径
	fs::path folderPath = "E:\\0数据集\\archive\\data\\Lung Segmentation\\CXR_png";

	// 检查文件夹是否存在
	if (!fs::exists(folderPath) || !fs::is_directory(folderPath)) {
		std::cerr << "Folder does not exist." << std::endl;
		return 1;
	}

	// 遍历文件夹中的所有文件
	for (const auto& entry : fs::directory_iterator(folderPath)) {
		std::cout << entry.path().filename() << std::endl;
	}

	return 0;
}

在上面的代码中,首先指定要遍历的文件夹路径,然后使用fs::directory_iterator来遍历文件夹中的所有文件。对于每个文件,我们输出其文件名。
需要注意的是,以上代码需要C++17标准及以上版本的支持。如果使用的是更早的C++标准,可能需要使用其他库或方法来实现相同的功能。

2.(C++11)获得指定目录下的所有文件(不搜索子文件夹)

在win10中,使用文件遍历函数_findnext会报0xC0000005错误
原因: _findnext()第一个参数”路径句柄”,返回的类型为intptr_t(long long),如果定义为long,在win7中是没有问题,但是在win10中就要改为long long或者intptr_t

//需要包含的头文件
#include <io.h>
#include <string>
#include <vector>
#include <fstream>

void getAllFiles(string path, vector<string>& files) 
{
	// 文件句柄
	//long hFile = 0;
	intptr_t hFile = 0;
	// 文件信息
	struct _finddata_t fileinfo;  

	string p;

	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
		do {
			// 跳过当前目录和父目录
			if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
			{
				// 保存文件的全路径
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		   } while (_findnext(hFile, &fileinfo) == 0);  //寻找下一个,成功返回0,否则-1

		_findclose(hFile);
	}
}

3.(C++11)获取目录下指定格式的所有文件(不搜索子文件夹)

void getFiles(string path, vector<string>& files, const char* sType)
{
	//文件句柄
	//long hFile = 0;
	intptr_t hFile = 0;
	//文件信息
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之
			//如果不是,加入列表
			if ((fileinfo.attrib & _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files,sType);
				}
			}
			else
			{
				char* pName = fileinfo.name;
				char* pFind = strstr(pName,sType);
				if (pFind != NULL)
				{
					files.push_back(p.assign(path).append("\\").append(fileinfo.name));
				}
			}
		} while (_findnext(hFile, &fileinfo) == 0);

		_findclose(hFile);
	}
}

4.(C++11)给文件重命名

int ReplaceFileName(const string oldFileName, string ModifyBeforeFilds, string ModifyAfterFilds)
{
	//临时文件名用于字符替换
	string newFileName = oldFileName;

	int findIndex = newFileName.find(ModifyBeforeFilds, 1);
	if (findIndex != -1)
	{
		newFileName = newFileName.replace(findIndex, ModifyBeforeFilds.size(), ModifyAfterFilds);
	}

	fstream fs;
	fs.open(oldFileName.c_str());
	if (fs.fail())
	{
		cout << "文件打开失败!" << endl;
		fs.close();
		return -1;
	}
	else
	{
		fs.close();
		if (rename(oldFileName.c_str(), newFileName.c_str()) == -1)   //文件重命名
		{
			cout << "文件名修改失败!" << endl;
			return -1;
		}
		cout << oldFileName << endl;
		cout << newFileName << endl;
		return 0;
	}
}

4. 测试

读取文件夹下的所有文件以及特定文件

int main()
 {
	// 指定要遍历的文件夹路径
	string folderPath = "E:\\0数据集\\archive\\data\\Lung Segmentation";
	vector<string> temp;
	getAllFiles(folderPath, temp, ".docx");
	for (int i = 0; i < temp.size(); ++i)
	{
		cout << temp[i] << endl;
	}
	return 0;
}

在这里插入图片描述
在这里插入图片描述

读取文件名后重命名

int main() 
{
	// 指定要遍历的文件夹路径
	string folderPath = "D:\\test1";
	vector<string> temp;
	getAllFiles(folderPath, temp, ".png");

	string ModifyBeforeFilds = "CHNCXR_";               //指定修改前的字段
	string ModifyAfterFilds = "image";                  //指定修改后的字段
	for (int i = 0; i < temp.size(); ++i)
	{
		cout << temp[i] << endl;
		int ret = ReplaceFileName(temp[i], ModifyBeforeFilds, ModifyAfterFilds);
		if (ret == 0)
		{
			cout << "文件重命名完毕!" << endl;
		}
	}
	return 0;
}

重命名前的文件:

在这里插入图片描述
重命名后的文件:

在这里插入图片描述
注意:当路径存在中文时,运行多次后出错,且不能成功重命名

参考文献

[1] C++:获取指定目录下的所有文件
[2] C++选择文件夹并获得其中所有文件路径
[3] C++获取文件夹下所有文件名并重命名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值