修改了一下程式,使其可以在當前路徑下以檔案名稱“遍曆結果.txt”輸出運行結果;
運行結果改為樹形輸出方式。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <stack>
#include <windows.h>
using namespace std;
/*
* 遍曆lpszPath下所有檔案及檔案夾,並按順序顯示其中的內容.
*/
/*
* 如果掃描到檔案夾,則將其存入 Dirs 隊列中,並顯示名稱,
* 如果掃描到檔案,則顯示其名稱;
* 當前檔案夾處理完畢後就處理其下一級檔案夾,下一級檔案夾從隊
* 列中得到.
*/
void function( LPCTSTR lpszPath,ostream & out)
{
//開始尋找;
stack<TCHAR*> Dirs;
stack<int> DirDepth;
TCHAR *tmp=new TCHAR[lstrlen(lpszPath)+1];
lstrcpy(tmp,lpszPath);
if(tmp[lstrlen(tmp)-1]=='//')
tmp[lstrlen(tmp)-1]='/0';
TCHAR szFind[MAX_PATH*2];
TCHAR szFile[MAX_PATH*2];
TCHAR *curdir;
int curdepth=1; //當前檔案夾的深度
Dirs.push(tmp);
DirDepth.push(curdepth);
for(;!Dirs.empty();)
{
curdir=Dirs.top();
curdepth=DirDepth.top();
Dirs.pop();
DirDepth.pop();
lstrcpy(szFind,curdir);
lstrcat(szFind, "//*.*"); // 找所有檔案
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(szFind, &wfd);
if (hFind != INVALID_HANDLE_VALUE) // 如果找到
{
if (curdepth >1)
out<<" ";
for(int i=1;i<curdepth-1;++i)
out<<'|'<<" ";
out<<'+'<<curdir<<endl;
do
{
if (wfd.cFileName[0] == '.')
continue; // 過濾"." ".." 這兩個目錄
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
wsprintf(szFile, "%s//%s", curdir, wfd.cFileName);
//function(szFile); // 如果找到的是目錄,則進入此目錄進行遞迴
TCHAR* tmp=new TCHAR[lstrlen(szFile)+2];
lstrcpy(tmp,szFile);
Dirs.push(tmp);
DirDepth.push(curdepth+1);
}
else
{
//輸出檔案名
out<<" ";
for(int i=1;i<curdepth;++i)
out<<'|'<<" ";
out<<wfd.cFileName<<endl;
}
} while (FindNextFile(hFind, &wfd));
}// if
delete [] curdir;
FindClose(hFind); // 關閉尋找控制代碼
}// for()
}
int main(int argc,char *argv[])
{
ofstream fout("遍曆結果.txt");
if(argc<=1)
{
cerr<<endl<<"檔案夾遍曆,請輸入路徑:";
TCHAR path[MAX_PATH];
cin>>path;
function(path,fout);
}
else
{
function(argv[1],fout);
}
return 0;
}