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 +"\" + file);var tmppath = filepath +"\" + 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,"\*.*");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,"\");strcat(szFile,FindFileData.cFileName); find(szFile);//递归调用} }else{ //printf("%s
",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
",filepath);start = clock();find(filepath); end = clock();printf("文件数:%d %dms max File:%d",count,end - start,maxsize);//system("PAUSE");}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!