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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章