//#include <dirent.h>
+ (long long) folderSizeAtPath3:(NSString*) folderPath{
return [self _folderSizeAtPath:[folderPath cStringUsingEncoding:NSUTF8StringEncoding]];
}
//Private
+ (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;
}