计算文件(文件夹)大小

- (long)fileSizeAtFile:(NSString *)file{
  // 1.文件管理者
   NSFileManager *mgr = [NSFileManager defaultManager];
    
    // 2.判断file是否存在
    BOOL isDirectory = NO;
    BOOL fileExists = [mgr fileExistsAtPath:file isDirectory:&isDirectory];
    // 文件文件夹不存在
    if (fileExists == NO) return 0;
    
    // 3.判断file是否为文件夹
    if (isDirectory) { // 是文件夹
        NSArray *subpaths = [mgr contentsOfDirectoryAtPath:file error:nil];
        long long totalSize = 0;
        for (NSString *subpath in subpaths) {
            NSString *fullSubpath = [file stringByAppendingPathComponent:subpath];
            totalSize += [self fileSizeAtFile:fullSubpath];
        }
        return totalSize;
    } else { // 不是文件夹, 文件
        // 直接计算当前文件的尺寸
        NSDictionary *attr = [mgr attributesOfItemAtPath:file error:nil];
        return [attr[NSFileSize] longLongValue];
      }
    }
   
原文地址:https://www.cnblogs.com/Fc-ios/p/3896123.html