21xrx.com
2025-06-10 22:39:22 Tuesday
文章检索 我的文章 写文章
C++如何获取文件的创建时间?
2023-07-06 04:06:26 深夜i     15     0
C++ 获取 文件 创建时间

在C++中,获取文件的创建时间可以通过系统调用函数来实现。具体来说,可以使用stat或stat64函数来获取文件的状态。这些函数包含在头文件sys/stat.h(或sys/stat64.h)中。

其中,stat函数的原型为:

int stat(const char *path, struct stat *buf);

其中,path是要获取状态的文件路径,buf是保存状态信息的结构体指针。

而stat64函数的原型为:

int stat64(const char *path, struct stat64 *buf);

其中,path和buf含义同上,只是buf结构体的成员类型是64位。

在结构体stat或stat64中,可以通过以下成员访问文件的创建时间:

- struct tm* st_ctime:指向一个tm结构体的指针,该结构体包含了文件的创建时间,包括秒、分、小时等信息。

因此,获取文件的创建时间可以按照以下步骤进行:

1. 定义一个struct stat或struct stat64结构体的指针;

2. 调用stat或stat64函数获取文件状态信息;

3. 通过结构体成员访问文件的创建时间。

以下是一个示例代码:

#include <iostream>
#include <sys/stat.h>
#include <time.h>
using namespace std;
int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    cout << "usage: " << argv[0] << " filename" << endl;
    return 0;
  }
  struct stat64 fileStat;
  if (stat64(argv[1], &fileStat) == -1)
  
    cout << "failed to get file status." << endl;
    return 0;
  
  struct tm* tmCreateTime = localtime(&fileStat.st_ctime);
  cout << "File created at "
     << tmCreateTime->tm_year + 1900 << "-"
     << tmCreateTime->tm_mon + 1 << "-"
     << tmCreateTime->tm_mday << " "
     << tmCreateTime->tm_hour << ":"
     << tmCreateTime->tm_min << ":"
     << tmCreateTime->tm_sec << endl;
  return 0;
}

在该代码中,首先判断命令行参数的个数,如果参数少于两个,输出用法并返回。接着,定义一个struct stat64结构体的指针fileStat,并调用stat64函数获取文件状态信息。如果获取失败,输出提示信息并返回。最后,通过结构体成员st_ctime获取文件的创建时间,并将时间信息输出。需要注意的是,用localtime函数将文件创建时间转换为tm结构体时需要注意时区的问题。

  
  

评论区