根据路径获取文件的大小

//单个文件的大小
-(long long) fileSizeAtPath:(NSString*) filePath{
    struct stat st;
    if(lstat([filePath cStringUsingEncoding:NSUTF8StringEncoding], &st) == 0){
        return st.st_size;
    }
    return 0;
}

// 获取某文件夹下所有文件的大小
- (long long)getFolderSize:(NSString *)folderPath
{
    // 找到folderPath路径下的所有文件夹
    NSArray *folderArr = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:folderPath error:nil];
    // 遍历文件夹
    NSEnumerator *filesEnumber = [folderArr objectEnumerator];
    NSString *fileName = nil;
    long long fileSize = 0;
    while (fileName = [filesEnumber nextObject]) {
        NSDictionary *fileDic = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:fileName] error:nil];
        fileSize += [fileDic fileSize];
    }

    return fileSize;
}

swift

//单个文件
func getFileSizeAtPath(filePath:String) ->Float{
        let manager = FileManager.default
        var fileSize:Float = 0.0
        if manager.fileExists(atPath: filePath) {
            do{
                let attr = try manager.attributesOfItem(atPath: filePath)
                fileSize = attr[FileAttributeKey.size] as! Float
            }catch{
            }
        }
        return fileSize
    }

//文件夹
func getFolderSizeAtPath(folderPath:String!) ->Float{

        let manager = FileManager.default
        var fileSize:Float = 0.0
        if manager.fileExists(atPath: folderPath) {
            do{
                let fileArr = try manager.contentsOfDirectory(atPath: folderPath)
                for i in 0..

你可能感兴趣的:(根据路径获取文件的大小)