文件夹:
首先导入头文件:
#include <sys/stat.h>
#include <dirent.h>
#define Localizable_LF_Size_Bytes @"%lld Bytes"
#define Localizable_LF_Size_K @"%lld K"
#define Localizable_LF_Size_M @"%lld.%lld M"
#define Localizable_LF_Size_G @"%lld.%d G"
#define Localizable_LF_All_Size_M @"%lld.%lld M"
#define Localizable_LF_All_Size_G @"%lld.%lld G"
-(long long) folderSizeAtPath:(NSString*) folderPath{
return [self _folderSizeAtPath:[folderPath 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_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;
}
/******************************************************************************
函数名称 : + (NSString *)stringForAllFileSize:(UInt64)fileSize
函数描述 : 格式话返回文件大小
输入参数 : (UInt64)fileSize
输出参数 : N/A
返回参数 : (NSString *)
备注信息 :
******************************************************************************/
-(NSString *)stringForAllFileSize:(UInt64)fileSize
{
if (fileSize<1024) {//Bytes/Byte
if (fileSize>1) {
return [NSString stringWithFormat:Localizable_LF_Size_Bytes,
fileSize];
}else {//==1 Byte
return [NSString stringWithFormat:Localizable_LF_Size_Bytes,
fileSize];
}
}
if ((1024*1024)>(fileSize)&&(fileSize)>1024) {//K
return [NSString stringWithFormat:Localizable_LF_Size_K,
fileSize/1024];
}
if ((1024*1024*1024)>fileSize&&fileSize>(1024*1024)) {//M
return [NSString stringWithFormat:Localizable_LF_All_Size_M,
fileSize/(1024*1024),
fileSize%(1024*1024)/(1024*102)];
}
if (fileSize>(1024*1024*1024)) {//G
return [NSString stringWithFormat:Localizable_LF_All_Size_G,
fileSize/(1024*1024*1024),
fileSize%(1024*1024*1024)/(1024*1024*102)];
}
return nil;
}
文件的大小:
long sizelong = [[[manager attributesOfFileSystemForPath:cacheDocPath error:nil] objectForKey:NSFileSize] longLongValue];