简体   繁体   中英

Last Modified of a File in Folder of C Program

My goal is to try to get the name, size and last modified of a folder. I have used dirent.h to get the first two types. I don't know what the best way of getting the last modified value is, but the current way I am using does not seem very useful. I am getting type errors when trying to get my path as the dirent folder that I am opening. I'm not sure if there is an easier way to do this or but any guidance would be much appreciated. I found an example of how to get the last modified on stackoverflow and was trying to use that... below is my code:



#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>

void getFileCreationTime(char *path) {
    struct stat attr;
    stat(path, &attr);
    printf("Last modified time: %s", ctime(&attr.st_mtime));
}

int main()
{
    DIR *folder;
    struct dirent *entry;
    int files = 0;

    folder = opendir(".");
    if(folder == NULL)
    {
        perror("Unable to read directory");
        return(1);
    }

    while( (entry=readdir(folder)) )
    {
        files++;
        printf("File %3d: %s\n",files, entry->d_name);
        printf("File %3d: %i\n",files, entry->d_reclen);
        getFileCreationTime(folder);
    }

    closedir(folder);

    return(0);
}

With error:

main.cpp: In function ‘int main()’:
main.cpp:36:35: error: cannot convert ‘DIR* {aka __dirstream*}’ to ‘char*’ for argument ‘1’ to ‘void getFileCreationTime(char*)’
         getFileCreationTime(folder);

Again, I am trying to be able to get the last modified date of each folder that I am getting the name and size of using dirent.

folder is the return value of opendir("."); . opendir returns either a DIR* structure or NULL. Not the directory path expressed using characters.

When you call getFileCreationTime(folder); you are sending a DIR* to your function. But you are expecting a char* path . So do not pass a DIR* , pass it the characters representing your directory. In your case "." (as used in your opendir() statement above).

Obviously, your directory name could be stored in a variable.

[...]

while( (entry=readdir(folder)) )
{
    files++;
    printf("File %3d: %s\n",files, entry->d_name);
    printf("File %3d: %i\n",files, entry->d_reclen);
    getFileCreationTime(".");
}

[...]

Using this, you will be able to read the time value. The name you already have.

For directory size, you will have to loop through the directory objects and add their size. You will have to decide what to do with sub-directories. Go down recursively or just take local objects? The source code of du would offer great insight (although it might be too complex for your need).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM