Last active
December 17, 2015 04:19
-
-
Save gmonnerat/5549919 to your computer and use it in GitHub Desktop.
Sample of code in C to sort large folders according to last modification.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Benchmark: | |
gabriel@localhost:~ $ ls ~/.mail/INBOX/cur | wc -l | |
8543 | |
gabriel@localhost:~ $ time ./sort ~/.mail/INBOX/cur > output | |
real 0m0.022s | |
user 0m0.000s | |
sys 0m0.024s | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <dirent.h> | |
#include <string.h> | |
#include <sys/stat.h> | |
struct File{ | |
int time,id; | |
}; | |
time_t get_st_mtime(const char *file_name) { | |
struct stat buf; | |
if (stat(file_name, &buf) != 0 ) return 0; | |
return buf.st_mtime; | |
} | |
struct File *File_create(int id, int time){ | |
struct File *file = malloc(sizeof(struct File)); | |
file->id = id; | |
file->time = time; | |
return file; | |
} | |
void *File_destroy(struct File *file){ | |
free(file); | |
} | |
int cmpfunc(const void * a, const void * b){ | |
struct File *a1 = *(struct File * const *)a; | |
struct File *b1 = *(struct File * const *)b; | |
return (b1->time-a1->time); | |
} | |
int main(int argc,char *argv[]){ | |
struct dirent **namelist; | |
int n,c=0,d,swap,i=0,f,s; | |
char *ch; | |
n = scandir(argv[1], &namelist, 0, NULL); | |
struct File **files = malloc(n*sizeof(struct File)); | |
while (n--) { | |
ch = namelist[n]->d_name; | |
if (strcmp(ch, ".") == 0 || strcmp(ch, "..") == 0){ | |
free(namelist[n]); | |
continue; | |
} | |
struct File *file = File_create(n, get_st_mtime(ch)); | |
files[c] = file; | |
c++; | |
} | |
qsort(files, c, sizeof(struct File *), cmpfunc); | |
for (i=0;i<c;i++){ | |
printf("%s\n", namelist[files[i]->id]->d_name); | |
free(namelist[files[i]->id]); | |
free(files[i]); | |
} | |
free(files); | |
free(namelist); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment