在c ++中获取文件或文件夹的创建日期

时间:2014-01-16 10:22:14

标签: c++ file

我想编写一个程序来获取我创建的文件和文件夹的详细信息,包括创建日期,如下所示: 2006年2月15日 我该怎么办?有什么建议吗? 我必须提到我不允许使用windows.h。

3 个答案:

答案 0 :(得分:5)

类似Linux的系统中,您可以使用stat函数:

#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;
}

Windows 中,我建议使用system()函数并从命令行获取文件时间:

#include <stdlib.h>

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

    return 0;
}

您可以将system()的输出重定向到例如一个临时文件并从那里解析日期。

或者使用此解决方法https://stackoverflow.com/a/40504396/1422630,这使得windows _stat与linux stat兼容,基本上是:

#ifdef WIN32
  #define stat _stat
#endif

答案 1 :(得分:1)

简单的答案是,你做不到。根据系统的不同, 可能有一个系统特定的功能,将执行此操作 (例如,Windows下的GetFileAttributesEx),但不是所有系统 甚至支持它;例如,Unix 保持这一点 信息,并没有办法在Unix系统上获取它 (或者在Unix系统上托管的文件系统 - 我 如果文件是,则不知道Windows函数将返回什么 物理托管在Unix系统上。)

答案 2 :(得分:0)

#include <sys/stat.h>

#include <unistd.h>

#include <time.h>



struct tm* clock;               // create a time structure

struct stat attrib;         // create a file attribute structure

stat("afile.txt", &attrib);     // get the attributes of afile.txt

clock = gmtime(&(attrib.st_mtime)); // Get the last modified time and put it into the time structure



// clock->tm_year returns the year (since 1900)

// clock->tm_mon returns the month (January = 0)

// clock->tm_mday returns the day of the month