C++基于递归的全目录文件查找

调用的数据结构和函数:

  • struct _finddata_t结构体
  • long _findfirst( char *filespec, struct _finddata_t *fileinfo )
  • int _findnext( long handle, struct _finddata_t *fileinfo )
    具体参数说明可以百度,或者看这篇博客

https://blog.csdn.net/yang332233/article/details/53081785

这是我刚学C++那段时间写来练手的,代码含金量一般,大佬轻喷

#include<iostream>
#include<string>
#include<io.h>
#include<windows.h>
#include<fstream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int getfile(string path,int n)//递归函数
{
	long hand;//
	int s = 0;
	string p = path + "\\*";//构造查询路径 * 是通配符
	string temp;
	struct _finddata_t fileinfo;//定义结构体
	hand = _findfirst(p.c_str(), &fileinfo);获取句柄
	if (hand == -1)//如果目录不存在直接退出查找
	{
		//cout<<"File cannot be found"<<endl;
		return 0;
	}
	do
	{
		if (strcmp(fileinfo.name, "..") == 0 || strcmp(fileinfo.name, ".") == 0)//跳过这两个目录,否者会出现目录混乱
			continue;
		if (fileinfo.attrib == _A_SUBDIR)//判断是否为目录
		{
			p = path + "\\" + fileinfo.name;
			getfile(p.c_str(),n+1);//如果是目录,构造查询path,执行getfile

		}
		//Sleep(100);
		else//如果是文件,将路径写入txt文件
		{
			fstream files;
			files.open("E:\\TEXT.txt", ios::out | ios::app);
			cout << fileinfo.name << endl;
			files << path + "\\" + fileinfo.name <<endl;
			files.close();
		}
	} while (_findnext(hand, &fileinfo) == 0);
	return 0;
}
int main()
{
	string filepath;
	char flag;
	cout << "请输入路径:" << endl;
	cin >> filepath;
	getfile(filepath,0);
	fflush(stdin);
	cout << "删除TEXT文件按d"<<endl;
	flag = getchar();
	if (flag == 'd') 
	if (remove("E:\\TEXT.txt") == 0) cout << "mission success" << endl;
	system("pause");
	return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Tomshidi

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

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

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

打赏作者

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

抵扣说明:

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

余额充值