iOS开发 - 获取沙盒文件夹大小

本文介绍了一种使用UnixC函数计算特定缓存文件夹大小的方法,包括导入必要的头文件、遍历目录并累加文件大小。特别关注了如何忽略隐藏目录和文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发过程中需要计算应用缓存,即需要计算某个缓存文件夹的大小,先研究如下,完全使用unix c函数
需要添加头文件
 //#include <sys/stat.h

 //#include <dirent.h>

+ (long long) folderSizeAtPath3:(NSString*) folderPath{

  return [self _folderSizeAtPath:[folderPath cStringUsingEncoding:NSUTF8StringEncoding]];

}

//Private

+ (long long) _folderSizeAtPath: (const char*)folderPath{

  long long folderSize = 0;

  DIR* dir = opendir(folderPath);

  if (dir == NULLreturn 0;

  struct dirent* child;

  while ((child = readdir(dir))!=NULL) {

    if (child->d_type == DT_DIR && (

                                    (child->d_name[0] == '.' && child->d_name[1] == 0) || // 忽略目录 .

                                    (child->d_name[0] == '.' && child->d_name[1] == '.' && child->d_name[2] == 0)// 忽略目录 ..

                                    )) continue;

    

    int folderPathLength = strlen(folderPath);

    char childPath[1024]; // 子文件的路径地址

    stpcpy(childPath, folderPath);

    if (folderPath[folderPathLength-1] != '/'){

      childPath[folderPathLength] = '/';

      folderPathLength++;

    }

    stpcpy(childPath+folderPathLength, child->d_name);

    childPath[folderPathLength + child->d_namlen] = 0;

    if (child->d_type == DT_DIR){ // directory

      folderSize += [self _folderSizeAtPath:childPath]; // 递归调用子目录

      // 把目录本身所占的空间也加上

      struct stat st;

      if(lstat(childPath, &st) == 0) folderSize += st.st_size;

    }else if (child->d_type == DT_REG || child->d_type == DT_LNK){ // file or link

      struct stat st;

      if(lstat(childPath, &st) == 0) folderSize += st.st_size;

    }

  }

  return folderSize;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值