iOS開發 - 獲取沙盒文件夾大小

開發過程中需要計算應用緩存,即需要計算某個緩存文件夾的大小,先研究如下,完全使用unix c函數
需要添加頭文件
 //#include <sys/stat.h

 //#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 == NULLreturn 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;

}

發佈了22 篇原創文章 · 獲贊 8 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章