【问题标题】:How to set the modification time of a file programmatically?如何以编程方式设置文件的修改时间?
【发布时间】:2011-01-12 05:20:32
【问题描述】:

如何在 Windows 中以编程方式设置文件的修改时间?

【问题讨论】:

    标签: c windows file


    【解决方案1】:

    发件人:http://rosettacode.org/wiki/File/Modification_Time#C

    #include <time.h>
    #include <utime.h>
    #include <sys/stat.h>
    
    const char *filename = "input.txt";
    
    int main() {
      struct stat foo;
      time_t mtime;
      struct utimbuf new_times;
    
      stat(filename, &foo);
      mtime = foo.st_mtime; /* seconds since the epoch */
    
      new_times.actime = foo.st_atime; /* keep atime unchanged */
      new_times.modtime = time(NULL);    /* set mtime to current time */
      utime(filename, &new_times);
    
      return 0;
    }
    

    【讨论】:

    • 您的 mtime 变量未使用,但除此之外是一个很好的答案。
    【解决方案2】:

    Windows(或标准 CRT,无论如何)具有与 UNIX 相同的 utimes 系列函数。

    struct _utimebuf t;
    t.tma = 1265140799;  // party like it's 1999
    t.tmm = 1265140799;
    _utime(fn, &t);
    

    使用Win32函数,可以使用SetFileInformationByHandle设置FILE_BASIC_INFO

    FILE_BASIC_INFO b;
    b.CreationTime.QuadPart = 1265140799;
    b.LastAccessTime.QuadPart = 1265140799;
    b.LastWriteTime.QuadPart = 1265140799;
    b.ChangeTime.QuadPart = 1265140799;
    b.FileAttributes = GetFileAttributes(fn);
    SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b));
    

    【讨论】:

    • 据我了解,windows 上的 _utime 不适用于目录,因为它们不被视为 windows 上的文件
    【解决方案3】:

    使用 SetFileInformationByHandle 和 FileInformationType 作为 FILE_BASIC_INFO

    【讨论】:

    • @bobbymcr,实际上尝试查找信息然后自己编写代码可能比期望其他人完成所有工作更有益。
    【解决方案4】:

    我发现这在 Windows SetFileTime() 上很有用

    【讨论】:

      【解决方案5】:
      【解决方案6】:

      这是达尔文的解决方案。 已删除所有安全措施。

      #include <sys/stat.h>
      #include <sys/time.h>
      
      // params
      char *path = "a path to a dir, a file or a symlink";
      long int modDate = 1199149200;
      bool followLink = false;
      
      // body
      struct stat currentTimes;
      
      struct timeval newTimes[2];
      
      stat(path, &currentTimes);
      
      newTimes[0].tv_sec = currentTimes.st_atimespec.tv_sec;
      newTimes[0].tv_usec = (__darwin_suseconds_t)0;
      newTimes[1].tv_sec = modDate;
      newTimes[1].tv_usec = (__darwin_suseconds_t)0;
      
      if (followLnk) {
          utimes(path, (const struct timeval *)&newTimes);
      } else {
          lutimes(path, (const struct timeval *)&newTimes);
      }
      

      【讨论】:

        猜你喜欢
        • 2011-03-06
        • 1970-01-01
        • 2013-07-30
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 2010-11-01
        相关资源
        最近更新 更多