【C++】获取文件夹下所有文件名并重命名

文章介绍了如何使用C++编写函数来获取指定路径下所有文件的名称,并在文件夹中不包含其他文件夹或包含其他文件夹的情况下,进行文件重命名。关键函数包括`GetAllFileName()`用于获取文件名和`ReplaceFileName()`用于重命名文件。当文件夹包含子文件夹时,通过迭代调用`GetAllFileName()`实现递归遍历并重命名所有符合条件的文件。
部署运行你感兴趣的模型镜像

一、函数功能说明

	1. `GetAllFileName()`获取指定路径下所有文件的名称
	2. `ReplaceFileName()`替换指定字段,重命名所有符合条件的文件名

二、文件夹中不包含其他文件夹

1. 代码

#include <iostream>
#include <io.h>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int GetAllFileName(const string RootPath, vector<string>& FilePathNames)
{
	string EachPath = RootPath;      //临时路径,用于字符拼接
	intptr_t FileHandle;             //文件句柄
	struct _finddata_t FileInfo;     //文件信息

	if ((FileHandle = _findfirst(EachPath.append("\\*").c_str(), &FileInfo)) == -1)
	{
		cout << "未找到文件! " << endl;
		return -1;
	}
	else
	{
		while (_findnext(FileHandle, &FileInfo) == 0)
		{
			if (strcmp(FileInfo.name, ".") != 0 && strcmp(FileInfo.name, "..") != 0)
			{
				FilePathNames.push_back(FileInfo.name);
				cout << "FileName : " << FileInfo.name << endl;
			}
		}
		_findclose(FileHandle);
	}
	return 0;
}

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;
		}
		return 0;
	}
}

int main()
{
	string Path = "C:\\Users\\Adiao\\Desktop\\Document";      //自定义路径
	vector<string> FilePathNames;                      //存放所有文件的路径名称
	string ModifyBeforeFilds = "张三";                 //指定修改前的字段
	string ModifyAfterFilds = "李四";                  //指定修改后的字段
	
	//获取所有文件名路径
	GetAllFileName(Path, FilePathNames);
	cout << "该路径下文件总数为:" << FilePathNames.size() << endl;
	for (auto name : FilePathNames)
	{
		string CompletePath = Path + "\\" + name;
		int ret = ReplaceFileName(CompletePath, ModifyBeforeFilds, ModifyAfterFilds);
		if (ret == 0)
		{
			cout << "文件重命名完毕!" << endl;
		}
	}

	system("pause");
	return 0;
}

2. 示例

场景:文件夹Document下只有文件,将所有文件名包含”张三“的文件重命名为”李四“。

修改前:

在这里插入图片描述

修改后:

在这里插入图片描述


三、文件夹中包含其他文件夹:迭代调用

1. 代码

#include <iostream>
#include <io.h>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int GetAllFileName(const string RootPath, vector<string>& FilePathNames)
{
	string EachPath = RootPath;      //临时路径,用于字符拼接
	intptr_t FileHandle;             //文件句柄
	struct _finddata_t FileInfo;     //文件信息

	//使用_findfirst查找文件,获取文件信息
	if ((FileHandle = _findfirst(EachPath.append("\\*").c_str(), &FileInfo)) == -1)
	{
		cout << "未找到文件! " << endl;
		return -1;
	}
	else
	{
		do
		{   // 比较文件类型是否是文件夹
			if ((FileInfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(FileInfo.name, ".") != 0 && strcmp(FileInfo.name, "..") != 0)
				{
					EachPath = RootPath;   //每次从根路径拼接
					//递归调用
					GetAllFileName(EachPath.append("\\").append(FileInfo.name), FilePathNames);
				}
			}
			else
			{
				EachPath = RootPath;
				FilePathNames.push_back(EachPath.append("\\").append(FileInfo.name));

				cout << "FileName : " << FileInfo.name << endl;
			}
		} while (_findnext(FileHandle, &FileInfo) == 0);
		_findclose(FileHandle);
	}
	return 0;
}

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;
		}
		return 0;
	}
}

int main()
{
	string Path = "C:\\Users\\Adiao\\Desktop\\Document";   //自定义路径
	string ModifyBeforeFilds = "张三";                     //指定修改前的字段
	string ModifyAfterFilds = "李四";                      //指定修改后的字段
	vector<string> FilePathNames;    //存放所有文件的路径名称

	//获取所有文件名路径
	GetAllFileName(Path, FilePathNames);

	cout << "该路径下文件总数为:" << FilePathNames.size() << endl;
	for (auto PathName : FilePathNames)
	{
		int ret = ReplaceFileName(PathName, ModifyBeforeFilds, ModifyAfterFilds);
		if (ret == 0)
		{
			cout << "文件重命名完毕!" << endl;
		}
	}

	system("pause");
	return 0;
}

2. 示例

场景:文件夹Document下包含其他文件夹,将所有文件夹中文件名包含”张三“的文件重命名为”李四“。

修改前:

在这里插入图片描述

在这里插入图片描述

修改后:

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

3. 说明

3.1 FileInfo.attrib文件属性

代码中使用if ((FileInfo.attrib & _A_SUBDIR))来判断是否为文件夹。

attrib:用于表示文件的属性,位表示,当一个文件有多个属性时,它往往是通过位或的方式,来得到几个属性的综合。

文件属性说明
1_A_ARCH存档
2_A_HIDDEN隐藏
3_A_NORMAL正常
4_A_RDONLY只读
5_A_SUBDIR文件夹
6_A_SYSTEM系统

如果这篇文章对你有所帮助,渴望获得你的一个点赞!

在这里插入图片描述

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

以下是使用C语言批量复制tif图片并重命名保存到新的文件夹下的示例代码: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char source_folder[100] = "./source/"; // 源文件夹路径,需要复制的tif图片所在文件夹 char target_folder[100] = "./target/"; // 目标文件夹路径,复制后的tif图片将保存在该文件夹下 char filename[100]; // 文件名 char new_filename[100]; // 新的文件名 int count = 1; // 文件计数器 // 打开源文件夹 DIR *dir; struct dirent *ent; if ((dir = opendir(source_folder)) != NULL) { // 循环遍历源文件夹中的所有文件 while ((ent = readdir(dir)) != NULL) { // 判断文件是否为tif图片 if (strstr(ent->d_name, ".tif") != NULL) { // 拼接文件路径 strcpy(filename, source_folder); strcat(filename, ent->d_name); // 打开源文件 FILE *source_file = fopen(filename, "rb"); if (source_file == NULL) { printf("Failed to open source file: %s\n", filename); continue; } // 构造新的文件名 sprintf(new_filename, "%s%d.tif", target_folder, count++); // 打开目标文件 FILE *target_file = fopen(new_filename, "wb"); if (target_file == NULL) { printf("Failed to create target file: %s\n", new_filename); fclose(source_file); continue; } // 复制文件内容 int c; while ((c = fgetc(source_file)) != EOF) { fputc(c, target_file); } // 关闭文件 fclose(source_file); fclose(target_file); } } closedir(dir); } else { printf("Failed to open source folder: %s\n", source_folder); return 1; } printf("Finished copying %d files.\n", count - 1); return 0; } ``` 在代码中,我们首先定义了源文件夹路径和目标文件夹路径,然后使用`opendir()`函数打开源文件夹,并循环遍历文件夹中的所有文件。对于每个文件,我们判断其是否为tif图片,然后打开源文件和目标文件,复制文件内容并保存到目标文件中,最后关闭文件。在复制文件时,我们使用了`fgetc()`和`fputc()`函数分别读取和写入文件内容。 需要注意的是,我们在复制文件时使用了计数器来生成新的文件名,如果源文件夹中存在同名的tif图片,则后面的文件会覆盖前面的文件。如果需要避免文件名冲突,可以使用其他的命名方式,例如在文件名中加入当前的时间戳等。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OpenC++

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值