linux遍历文件夹下所有文件大小,Linux系统遍历文件夹 获取文件大小的操作(C语言实现)...

/**

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;

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值