Write your own shell command du

Source: Internet
Author: User
Tags lstat strcmp

The du command can view the number of tiles occupied by the specified folder, and the following is the code for the C language implementation of the Shell du Directive under Linux (Support-k option):

#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 (pa Thname)) = = 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;}


Write your own shell command du

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.