0

I have a problem with checking the modification date. fprintf prints in the console for every file in the folder the same number equal zero.

while (1) {
    source = opendir(argv[1]);
    while ((file = readdir(source)) != NULL) {
        if (file->d_type != DT_REG)
            continue; 
        stat(file->d_name, &file_details);
        fprintf(stderr, "Name: %s, Last modify: %ld  \n", file->d_name, file_details.st_mtime);
    }
    closedir(source);
    sleep(5);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
kamilm758
  • 51
  • 5

1 Answers1

0

You must construct the path to the directory entry ans pass it to stat. You currently pass the entry name, which only works if you are enumerating from the current directory.

Furthermore, you should test the return value of stat to detect any problem. This would have shown that stat fails with the current code.

Here is a modified version:

#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

...

char path[1024];
while (1) {
    source = opendir(argv[1]);
    if (source == NULL)
        break;
    while ((file = readdir(source)) != NULL) {
        if (file->d_type != DT_REG)
            continue; 
        snprintf(path, sizeof path, "%s/%s", path, file->d_name);
        if (!stat(path, &file_details))
            fprintf(stderr, "Name: %s, Last modify: %ld\n", path, file_details.st_mtime);
        else
            fprintf(stderr, "Cannot stat %s; %s\n", path, strerror(errno));
    }
    closedir(source);
    sleep(5);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189