歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux C程序實現文件夾大小提取

Linux C程序實現文件夾大小提取

日期:2017/3/1 11:09:22   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved