node.js版
遍歷文件夾下最大的文件,并輸出路徑,大小
實現代碼:
/* 遍歷文件夾下最大的文件,并輸出路徑,大小*/ function findmax(basepath){ //只能執行一次 if(findmax.s) return; findmax.s = true; var fs = require('fs'); var maxfile = 0; var count = 0; var begin = new Date().getTime(); function Traversal(filepath){ fs.readdir(filepath, function(err,files){ if(err) return; files.forEach(function(file,index,files){ //console.log(index + "=" + filepath +"http://" + file); var tmppath = filepath +"http://" + file; fs.stat(tmppath, function (err, stats) { if (err) { console.log("打開文件錯誤" + err); return; }; if(stats.isDirectory()) Traversal(tmppath); else { //console.log(++count +" "+ tmppath + " " + stats.size); count++; if(maxfile < stats.size) maxfile = stats.size; } }); }); }); } Traversal(basepath); process.on('exit', function () { var end = new Date().getTime(); console.log(count + '結束耗時:' + (end - begin) + "ms " + maxfile); }); console.log(basepath);} findmax('D://devtools//');
C/C++實現代碼
#include <stdio.h> #include <windows.h>#include <time.h> DWORD maxsize = 0;clock_t start, end;DWORD count = 0; void find(char * lpPath) { char szFind[MAX_PATH],szFile[MAX_PATH]; DWORD tmpsize = 0; WIN32_FIND_DATA FindFileData; strcpy(szFind,lpPath); strcat(szFind,"http://*.*"); HANDLE hFind=FindFirstFile(szFind,&FindFileData); if(INVALID_HANDLE_VALUE == hFind) return; while(TRUE) { if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)//如果為目錄 { if(FindFileData.cFileName[0] != '.') //判斷是否為. or .. { strcpy(szFile,lpPath); strcat(szFile,"http://"); strcat(szFile,FindFileData.cFileName); find(szFile);//遞歸調用 } }else{ //printf("%s/n",FindFileData.cFileName); count++;//文件計數 tmpsize = FindFileData.nFileSizeLow; if(maxsize < tmpsize) maxsize = tmpsize; } //下一個文件為空,則退出 if(!FindNextFile(hFind,&FindFileData)) break; } } void main() { char filepath[MAX_PATH]="d://devtools"; printf("%s/n",filepath); start = clock(); find(filepath); end = clock(); printf("文件數:%d %dms max File:%d",count,end - start,maxsize); //system("PAUSE");}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答