1.du命令
这里显示他的文件大小是4K
我们可以看到它占了八个块,就是4K
2.自己写的一个简单的MyDU
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <glob.h>
#include <string.h>
#define MAXSIZE 1024
//当前目录下面 有两个隐藏文件 . 和 .. 不加处理会造成无限递归
int PathNoLoop(const char *pPath)
{
char *pPos;
// aaa/bbb/ccc/..
//获取最右边的/出现的位置
pPos = strrchr(pPath, '/');
if(NULL == pPos)
{
exit(1);
}
if(0 == strcmp(pPos+1 , ".") || 0 == strcmp(pPos+1, ".."))
{
return 0;
}
return 1;
}
int DU(const char *pPath)
{
struct stat FileStat;
char Pattern[MAXSIZE] = "";
int i = 0;
glob_t GlobRes;
int sum = 0;
if(0 > lstat(pPath, &FileStat))
{
perror("lstat\n");
exit(1);
}
//如果不是一个目录的话
if(!S_ISDIR(FileStat.st_mode))
{
//直接返回块大小
return FileStat.st_blocks;
}
//否则就是目录了
//我们要对其加上/* 添加上目录下面的文件(除了隐藏文件)
strncpy(Pattern , pPath, MAXSIZE);
strncat(Pattern, "/*", MAXSIZE);
glob(Pattern, 0, NULL , &GlobRes);
//然后在其后面追加隐藏文件
strncpy(Pattern, pPath, MAXSIZE);
strncat(Pattern, "/.*", MAXSIZE);
glob(Pattern, GLOB_APPEND, NULL, &GlobRes);
for(i = 0; i < GlobRes.gl_pathc; i++)
{
//不会造成无限递归的话
if(PathNoLoop(GlobRes.gl_pathv[i]))
{
sum += DU(GlobRes.gl_pathv[i]);
}
}
globfree(&GlobRes);
return sum;
}
int main(int argc, char **argv)
{
if(argc < 2)
{
fprintf(stderr,"No Enough argc\n");
exit(1);
}
printf("%d\n", DU(argv[1])/2);
return 0;
}