檔案夾:
首先匯入標頭檔:
#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];
參考:http://www.easymorse.com/index.php/archives/638