获取文件夹大小
本站寻求有缘人接手,详细了解请联系站长QQ1493399855
IOS里面没有获取整个目录里面所有文件大小的函数,所以只能遍历然后累加。
//获取文件大小
+(long long)getFileSize:(NSString*)filePath
{
return [self _folderSizeAtPath:[filePath cStringUsingEncoding:NSUTF8StringEncoding]];
}
+ (long long) _folderSizeAtPath: (const char*)folderPath
{
long long folderSize = 0;
DIR* dir = opendir(folderPath);
if (dir == NULL) return 0;
struct dirent* child;
while ((child = readdir(dir))!=NULL)
{
if (child->d_type DT_DIR &&,,,,,,,,,,,,,,,,,,,,,, (
(child->d_name[0] '.' && child->d_name1 0) || // 忽略目录 .
(child->d_name[0] '.' && child->d_name1 '.' && 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;
}