您的位置:首页 > 编程语言 > C语言/C++

C/C++ 如何遍历文件夹中最大的那一个文件

2016-03-05 00:00 483 查看
摘要: 在这里我为大家介绍一个快速查找文件夹中最大的一个文件的方法!!!当中用到while方法.另外又附上了node.js版的.希望大家多多交流.

1. [代码][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");


}




?

2. [代码]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\\'

);



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息