自己動手寫shell命令之du

來源:互聯網
上載者:User

標籤: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);elseprintf("%-5.5d %s\n",sum/2,pathname);return sum;}


自己動手寫shell命令之du

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.