自己动手写shell命令之du
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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。