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

Jay*_*Jay 7 c windows file

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

DVK*_*DVK 15

来自: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;
}
Run Code Online (Sandbox Code Playgroud)


eph*_*ent 7

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

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

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

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));
Run Code Online (Sandbox Code Playgroud)