调用的数据结构和函数:
- 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;
}