1

I'm trying to display the files of my current working directory in C, however, I also need to include the details of these files such as the date created and their file sizes.

Is there a function that does this in C?

So far here is my code:

int main(
    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    if (d) {
        while ((dir = readdir(d)) != NULL) {
            printf("%s\n", dir->d_name);
        }
        closedir(d);
    }
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256

1 Answers1

4

File information is handled not by dirent functions, but by stat().

Note stat() requires a pathname; combining the directory path with the file name from the dirent structure (using strncat) will give you the necessary argument. In this particular case, since file information is only needed for files in the current working directory, the path can be left off and the file name can be used directly as the argument (stat() will then look for the file in the current directory).

The stat struct has the various entries you're interested in, such as st_size for file size and st_ctime for change time (note the latter is a UNIX time, which you'll likely want to convert to a readable string).

outis
  • 75,655
  • 22
  • 151
  • 221