1. 程式人生 > >C++基於遞迴的全目錄檔案查詢

C++基於遞迴的全目錄檔案查詢

呼叫的資料結構和函式:

  • struct _finddata_t結構體
  • long _findfirst( char *filespec, struct _finddata_t *fileinfo )
  • int _findnext( long handle, struct _finddata_t *fileinfo ) 具體引數說明可以百度,或者看這篇部落格

這是我剛學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;
}