標籤: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