/***************************************************************************** * * Program: dirsize * * This C program simulates the dir/size command on a VMS machine. * * To compile and link this program in Linux/Unix: * * > gcc -o dirsize dirsize.c * * Written by Don Luttermoser on 6 Jun 1995. * Last modified on 7 Feb 1999 * Last modified on 13 Sep 2021. * Last modified on 28 May 2025: * - Reposition header words. * - Added to "include". * *****************************************************************************/ #include #include #include #include #define STRMAX 255 #define DIRMAX 255 int main(int argc, char *argv[]) { int count = 0, digcnt, i, c, nchar = 0; long int sz, szfile = 0, szvms; double fscale = 1.; char line[STRMAX], size[STRMAX], command[STRMAX], cdir[STRMAX], funit[10]; FILE *fp, *fls; if ((fp = popen("pwd", "r")) != NULL) { /* Get the directory name */ i = 0; while (((c = getc(fp)) != EOF) && (i < STRMAX-1)) cdir[i++] = c; cdir[i] = '\0'; fflush(fp); pclose(fp); } else { fprintf(stderr, "Error in reading contents of current directory.\n"); exit(EXIT_FAILURE); } switch (argc) { case 1: fls = popen("ls -l", "r"); /* Get a "long" listing of the files in dir */ break; default: strcpy(command, "ls -l "); for (i = 0; i < argc; i++) { strcat(command, argv[i]); strcat(command, " "); if ((strchr(argv[i], '/')) != NULL) { /* Check for different dir. */ if (i == 1) { strcpy(cdir, argv[i]); strcat(cdir, " "); } else { strcat(cdir, argv[i]); strcat(cdir, " "); } strcat(cdir, "\n"); } } fls = popen(command, "r"); /* Get a "long" listing of the files */ break; } if (fls == NULL) { fflush(fls); pclose(fls); fprintf(stderr, "Error in reading contents of directory: %s\n", cdir); exit(EXIT_FAILURE); } /* Read the values in fls stream. */ while (((c = getc(fls)) != EOF)) { if (c != '\n') { line[nchar++] = c; } else { line[nchar] = '\0'; nchar = 0; /* Note that the first line in the total line is not needed here. */ if (count == 0) { printf("\nDirectory: %s\n", cdir); printf("Protection Owner Group Size Created "); printf(" Filename\n"); printf(" (bytes) (day/time)\n"); count++; } else { if ((strncmp(line, "total", 5)) != 0) printf("%s\n", line); digcnt = 0; for (i = 0; line[i] != '\0'; i++) { if (i >= 31 && i <= 40) { if (isdigit(line[i])) size[digcnt++] = line[i]; } } if (digcnt > 0) { szfile = szfile + atol(size); count++; for (i = 0; i < STRMAX; i++) size[i] = '\0'; /* Flush last value */ } } } } fflush(fls); pclose(fls); szvms = (long int) ((double)szfile/512. + 0.5); strcpy(funit, "Bytes"); if (szfile > 1000l) { fscale = 1000.; strcpy(funit, "KiloBytes"); } if (szfile > 1000000l) { fscale = 1.e6; strcpy(funit, "MegaBytes"); } if (szfile > 1000000000l) { fscale = 1.e9; strcpy(funit, "GigaBytes"); } printf("\nTotal of %d files, at %.2f %s, or %ld (512-byte, VMS) blocks.\n\n", count-1, (double)szfile/fscale, funit, szvms); exit(EXIT_SUCCESS); }