Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the creation date of file or folder in c++

Tags:

c++

file

I want to write a program to get the details of files and folder I created including the creation date like this: Feb 15 2006 What should I do? Any suggestion? And I have to mentioned that I'm not allowed to use windows.h .

like image 837
user3202024 Avatar asked Dec 19 '22 19:12

user3202024


2 Answers

The simple answer is that you can't. Depending on the system, there may be a system specific function which will do this (e.g. GetFileAttributesEx under Windows), but not all systems even support it; Unix, for example, does not keep this information, and there is no way to obtain it on a Unix system (or on a file system which is hosted on a Unix system—I don't know what the Windows function will return if the file is physically hosted on a Unix system).

like image 22
James Kanze Avatar answered Dec 29 '22 10:12

James Kanze


In Linux-like system, you can use the stat function, as such:

#include <sys/stat.h>
#include <time.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    struct stat t_stat;
    stat("file_name", &t_stat);
    struct tm * timeinfo = localtime(&t_stat.st_ctime); // or gmtime() depending on what you want
    printf("File time and date: %s", asctime(timeinfo));

    return 0;
}

In Windows, I'd suggest using the system() function and get file time from commandline:

#include <stdlib.h>

int main(int argc, char **argv)
{
    system("dir /T:C file_name");

    return 0;
}

You can redirect output of system() to e.g. a temporary file and parse the date from there.

Or use this workaround https://stackoverflow.com/a/40504396/1422630, that makes windows' _stat compatible with linux one stat, basically:

#ifdef WIN32
  #define stat _stat
#endif
like image 138
the swine Avatar answered Dec 29 '22 10:12

the swine