码迷,mamicode.com
首页 > 系统相关 > 详细

自己动手写shell命令之du

时间:2014-10-16 19:19:32      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:unix环境高级编程   linux   shell   

du命令可以查看指定文件夹占用的磁块数,以下为linux下c语言实现shell du指令的代码(支持-k选项):

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int disk_usage(char *);

int k = 0;

int main(int argc,char * argv[])
{
	int i;
	for(i = 1;i < argc;i++)
	{
	    if(strcmp(argv[i],"-k") == 0)
	    {
	         k = 1;
	         break;
	    }
	}
	if(argc == 1 && k == 0)
		disk_usage(".");
	else if(argc == 2 && k == 1)
		disk_usage(".");
	else
	{
	    int index = 1;
	    while(argc > 1)
	    {
	        if(strcmp(argv[index],"-k") != 0)
	        	disk_usage(argv[index]);
	        index++;
	        argc--;
	    }
	}
	return 0;
}

int disk_usage(char * pathname)
{
	DIR * dir;
	int sum = 0;
	struct dirent * direntp;
	struct stat stat_buffer;
	if((dir = opendir(pathname)) == NULL)
	{
		perror("error");
		exit(1);
	}
	while((direntp = readdir(dir)) != NULL)
	{
		char absolute_pathname[255];
		strcpy(absolute_pathname,pathname);
		strcat(absolute_pathname,"/");
		strcat(absolute_pathname,direntp->d_name);
		if(strcmp(direntp->d_name,".") == 0 || strcmp(direntp->d_name,"..") == 0)
		{
			if(strcmp(direntp->d_name,".") == 0)
			{
				lstat(absolute_pathname,&stat_buffer);
				sum = sum + stat_buffer.st_blocks;
			}
			continue;
		}
		lstat(absolute_pathname,&stat_buffer);
		if(S_ISDIR(stat_buffer.st_mode))
		{
			//sum = sum + stat_buffer.st_blocks;
			sum = sum + disk_usage(absolute_pathname);
		}
		else
		{
			sum = sum + stat_buffer.st_blocks;
		}
	}
//	lstat(pathname,&stat_buffer);
//	sum = sum + stat_buffer.st_blocks;
	if(k == 0)
		printf("%-5.5d %s\n",sum,pathname);
	else
		printf("%-5.5d %s\n",sum/2,pathname);
	return sum;
}


自己动手写shell命令之du

标签:unix环境高级编程   linux   shell   

原文地址:http://blog.csdn.net/yao_wust/article/details/40151461

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!