HugoB HugoB - 1 year ago 90
C Question

How to print a list of filename from a directory by date in C?

I wanna print the name of every filename from a directory by date. I have sorted every date but I wanna associate every name with its date. Is there a function or a method to do that?

#define BUFFERSIZE 100

char SORTNAME() {
DIR *dir = opendir(".");
if (dir) {
char buffer[BUFFERSIZE];
struct stat info;
struct dirent *s_dir;
int buf = BUFFERSIZE;
time_t *Time = malloc(sizeof(time_t) * buf);
int i = 0;

while ((s_dir = readdir(dir)) != NULL) {
if (s_dir->d_name[0] != '.') {
sprintf(buffer, "%s", s_dir->d_name);
stat(buffer, &info);
Time[i] = info.st_mtime;

int size = i;
int h, j, k, min;
time_t t;

for (j = 0; j < size - 1; j++) {
min = j;
for (k = j + 1; k < size; k++) {
if (Time[k] > Time[min]) {
min = k;
t = Time[min];
Time[min] = Time[j];
Time[j] = t;

It's a bit rudimental but it works.

Answer Source

You should follow these steps:

  • store the filenames and the dates in an array of structures, reallocating the array if there are more files than expected. Make sure you allocate copies of the filenames.
  • sort the array with qsort and an appropriate sorting function. Try using different sorting functions to sort by file time, name, extension...
  • print the entries in the order of the array. Converting the file time can be done with strftime()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download