您的位置:首页 > 运维架构 > Linux

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

2011-07-31 11:00 267 查看
http://lizzy115.blog.163.com/blog/static/36491958201010254255320/


在嵌入式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/



下面的程序使用statfs函数实现硬盘大小数据提取,及剩余空间大小的提取,并把硬盘大小及剩余空间打印出来。

#include <stdio.h>;

#include <sys/vfs.h>;

#include <error.h>;

#define Gsize (1024.00*1024.00*1024.00)

#define Msize (1024.00*1024.00)

#ifndef EXT2_SUPER_MAGIC

#define EXT2_SUPER_MAGIC 0xef53

#endif

int main()

{

long long blocks,bfree;

struct statfs fs;

if(statfs("/",&fs)<0)

{

perror("statfs");

exit(0);

}

printf("%x\n",fs.f_type); /* type of filesystem (see below) */

printf("%ld\n",fs.f_bsize); /* optimal transfer block size */

printf("%ld\n",fs.f_blocks); /* total data blocks in file system */

printf("%ld\n",fs.f_bfree); /* free blocks in fs */

printf("%ld\n",fs.f_bavail); /* free blocks avail to non-superuser */

printf("%ld\n",fs.f_files); /* total file nodes in file system */

printf("%ld\n",fs.f_ffree); /* free file nodes in fs */

printf("%d\n",fs.f_fsid); /* file system id */

printf("%ld\n",fs.f_namelen); /* maximum length of filenames */

blocks=fs.f_blocks;

bfree=fs.f_bfree;

printf(" %lld\n",blocks);

if(fs.f_type==EXT2_SUPER_MAGIC)

{

printf("Total size of / is %f G\n",blocks*fs.f_bsize/Gsize);

printf("Free size of / is %f G\n",bfree*fs.f_bsize/Gsize);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: