Mega Code Archive

 
Categories / C / Small Application
 

Snippit, sort directory entrys by filesize

#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #define PACKAGE "dirsort" #define VERSION "0.0.1" struct fnode { char *filename; int filesize; }; /* compare function for qsort */ static int cmpr(const void *a, const void *b); /* print help.... and exit program with exval */ void print_help(int exval); int main(int argc, char *argv[]) { struct fnode **drarray = NULL; char *dir = argv[1]; struct dirent *entry; struct stat statbuf; int count = 0, i = 0; DIR *dp; if(argc == 1) print_help(0); if((dp = opendir(dir)) == NULL) { fprintf(stderr, "%s: Error - opendir(%s)\n", PACKAGE, dir); return 1; } if(chdir(dir) == -1) { fprintf(stderr, "%s: Error - chdir(%s)\n", PACKAGE, dir); return 1; } while((entry = readdir(dp)) != NULL) { if(stat(entry->d_name, &statbuf) == -1) { fprintf(stderr, "%s: Error - stat(%s)\n", PACKAGE, entry->d_name); return; } if(S_ISREG(statbuf.st_mode)) { /* NOTE: no error checking... ! */ /* add ONE element to the array */ drarray = (struct fnode **)realloc(drarray, (count + 1) * sizeof(struct fnode *)); /* allocate memory for ONE `struct node` */ drarray[count] = (struct fnode *)malloc(sizeof(struct fnode)); /* copy the data into the new element (structure) */ drarray[count]->filename = strdup(entry->d_name); drarray[count]->filesize = statbuf.st_size; count++; } } closedir(dp); /* qsort array of structures */ qsort(drarray, count, sizeof(*drarray), cmpr); /* print it ... */ for(i = 0; i < count; i++) printf("%8d\t%s\n", drarray[i]->filesize, drarray[i]->filename); /* free all drarray elements */ for(i = 0; i < count; i++) { free(drarray[i]->filename); free(drarray[i]); } free(drarray); return 0; } /* compare function for qsort */ static int cmpr(const void *a, const void *b) { struct fnode * const *one = a; struct fnode * const *two = b; int retval = 0; if((*one)->filesize < (*two)->filesize) retval = -1; else if((*one)->filesize > (*two)->filesize) retval = 1; else retval = 0; return retval; } void print_help(int exval) { printf("%s,%s example, sort a directory by filesize\n", PACKAGE, VERSION); printf("Usage: %s DIRECTORY\n\n", PACKAGE); printf(" Options:\n"); printf(" No options.. this is just some small code fragment\n"); printf(" to get started..\n\n"); exit(exval); }