Linux C程序实现文件夹大小提取


在嵌入式Linux系统中,经常要对一些实时数据进行存储,而在存储空间有限的情况下往往需要判断存储目录中的文件夹的大小,而通过C语言实现文件夹大小的获取在网上的程序可是少之又少,现提供一个程序,大家一起分享,分享,其实程序是提取文件夹下所有文件大小,提取运行程序文件夹下的文件的大小之和,但不包括文件夹目录下的文件夹的大小。

体程序如下:

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
 
main()
{
  DIR *d;
  struct dirent *de;
  struct stat buf;
  int exists;
  int total_size;
 
  d = opendir(".");
  if (d == NULL) {
    perror("prsize");
    exit(1);
  }
 
  total_size = 0;
 
  for (de = readdir(d); de != NULL; de = readdir(d)) {
    exists = stat(de->d_name, &buf);
    if (exists < 0) {
      fprintf(stderr, "Couldn't stat %s\n", de->d_name);
    } else {
      total_size += buf.st_size;
    }
  }
  closedir(d);
  printf("%d\n", total_size);
}

以下为另外一个文件夹大小提取程序,程序内容:

#include <stdio.h> 
#include <errno.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 

static unsigned int total = 0; 

int sum(const char *fpath, const struct stat *sb, int typeflag)

     total += sb->st_size; 
     return 0; 

 } 
 

int main(int argc, char **argv)
 { 

     if (!argv[1] || access(argv[1], R_OK)) { 

         return 1; 

     } 

     if (ftw(argv[1], &sum, 1)) { 

         perror("ftw"); 

         return 2; 

     } 

    printf("%s: %u\n", argv[1], total); 

     return 0; 

 }

 

通过GCC编译程序
gcc -o dir_size dir_size.c

运行程序
./dir_size /licy/

  • 1
  • 2
  • 下一页

相关内容