欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

node.js与C语言 实现遍历文件夹下最大的文件,并输出路径,大小

程序员文章站 2023-11-03 14:00:10
node.js版     遍历文件夹下最大的文件,并输出路径,大小 实现代码: /* 遍历文件夹下最大的文...

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\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");
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!