<pre code_snippet_id= "1622396" snippet_file_name= "blog_20160324_1_744516" name= "code" class= "CPP" > Traverse the directory to get the entire directory footprint:
uint64_t Dir_space (char *path) {int ret = 0; uint64_t space = 0; Char Cur_dir[path_max + 1] = {0}; DIR *dir = NULL; struct Dirent *ent = NULL; if (NULL = = path) {return 0; dir = opendir (path); if (NULL = = dir) {return 0; } if (NULL = = GETCWD (Cur_dir, Path_max)) {Closedir (dir); return 0; } chdir (path); printf ("Current dir is%s\n", path); ent = Readdir (dir); while (NULL! = ent) {if (strcmp (Ent->d_name, ".") = = 0 | | strcmp (Ent->d_name, "..") = = 0) { Space + = 4096; Goto GOON; } if (Ent->d_type = = Dt_dir) {space + = 4096; Space + = Dir_space (ent->d_name); } else {struct STAT st; Lstat (Ent->d_name, &st); Space + = St.st_size; }goon:ent = Readdir (dir); } chdir (Cur_dir); Closedir (dir); printf ("Out of dir%s\n", path); RetuRN Space;}
Linux Traversal directory source code