node. js and C language traversal folder under the largest file and output path size

  • 2021-07-13 03:50:23
  • OfStack

node. js version

Traverse the largest file under the folder and output the path and size

Implementation code:


/*
   Traverse the largest file under the folder and output the path and size 
*/
 
function findmax(basepath){
  // Can only be executed 1 Times 
  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(" Error opening file " + 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 time consuming :' + (end - begin) + "ms " + maxfile);
  }); 
  console.log(basepath);
}
 
findmax('D:\\devtools\\');

C/C + + Implementation Code


#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 it is a directory 
    { 
      if(FindFileData.cFileName[0] != '.') // Determine whether it is . or ..
      { 
        strcpy(szFile,lpPath);
        strcat(szFile,"\\");
        strcat(szFile,FindFileData.cFileName); 
        find(szFile);// Recursive invocation 
      } 
    }else{ 
      //printf("%s\n",FindFileData.cFileName);
      count++;// File count 
      tmpsize = FindFileData.nFileSizeLow;
      if(maxsize < tmpsize)  maxsize = tmpsize;
    }
    // Under 1 If the files are empty, exit 
    if(!FindNextFile(hFind,&FindFileData)) break; 
  } 
} 
 
void main() 
{ 
  char filepath[MAX_PATH]="d:\\devtools"; 
  printf("%s\n",filepath);
  start = clock();
  find(filepath); 
  end = clock();
  printf(" Number of files :%d %dms max File:%d",count,end - start,maxsize);
  //system("PAUSE");
}

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: