/**
linux 下遍历文件夹以及获取文件大小
*/
#include
#include
#include
#include
/** 获取文件大小,但是文件大小不能超过2G ,该方法不推荐使用 */
unsigned long get_file_size_small(const char *filename)
{
FILE *pFile = NULL;
int iRet = 0;
unsigned long ulFileSize = 0;
pFile = fopen(filename, "rb");
if (NULL == pFile)
{
return -1;
}
iRet = fseek(pFile, 0, SEEK_END); //seek到文件末尾
if (0 != iRet)
{
return -1;
}
ulFileSize = ftell(pFile);
fclose(pFile);
return ulFileSize;
}
/** 获取文件大小,推荐使用该方法 */
unsigned long get_file_size(const char *filename)
{
struct stat buf;
if(stat(filename, &buf)<0)
{
return 0;
}
return (unsigned long)buf.st_size;
}
/** 遍历文件夹 */
int travel_dir(const char *pcDirName)
{
struct dirent *pstDirent = NULL;
DIR* pDir = NULL;
char childBuf[512] = {0};
if (NULL == pcDirName)
{
return -1;
}
pDir = opendir(pcDirName);
if (NULL == pDir)
{
return -1;
}
while (NULL != (pstDirent=readdir(pDir)))
{
if (pstDirent->d_type & DT_DIR) //目录
{
/** 跳过. , ..文件夹。这些是linux系统自带的隐藏目录*/
if (0==strcmp(pstDirent->d_name, ".") || 0==strcmp(pstDirent->d_name, ".."))
{
continue;
}
/** 打印出文件夹的名字 */
printf("[d]%s\n", pstDirent->d_name);
/** 传入子文件夹路径,递归调用*/
memset(childBuf, 0, sizeof(childBuf));
snprintf(childBuf, sizeof(childBuf), "%s/%s", pcDirName, pstDirent->d_name);
travel_dir(childBuf);
}
/** 字符设备为DT_CHR =4, 块设备为DT_BLK = 6,普通文件为DT_REG = 8,link为DT_LNK = 10
DT_FIFO,命名管道或FIFO,DT_SOCK,本地套接口*/
else
{
memset(childBuf, 0, sizeof(childBuf));
snprintf(childBuf, sizeof(childBuf), "%s/%s", pcDirName, pstDirent->d_name);
printf("%s\t%d\n", pstDirent->d_name, get_file_size(childBuf));
}
}
closedir(pDir);
return 0;
}