10

How do I set the modification time of a file programmatically in Windows?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
Jay
  • 24,173
  • 25
  • 93
  • 141

6 Answers6

18

From: 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;
}
DVK
  • 126,886
  • 32
  • 213
  • 327
8

Windows (or the standard CRT, anyhow) has the same utimes family of functions that UNIX has.

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

Using Win32 functions, FILE_BASIC_INFO can be set using 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));
ephemient
  • 198,619
  • 38
  • 280
  • 391
2

Use SetFileInformationByHandle with FileInformationType as FILE_BASIC_INFO

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
  • @bobbymcr, and actually trying to find the information and then code it themselves might be more beneficial than expecting someone else to do all the work. – Lazarus Feb 02 '10 at 16:00
1

I found this to be useful on windows SetFileTime()

GingerJack
  • 3,044
  • 1
  • 17
  • 19
0

See http://msdn.microsoft.com/en-us/library/aa365539%28VS.85%29.aspx

kolbyjack
  • 17,660
  • 5
  • 48
  • 35
0

Here is the solution for Darwin. All security removed.

#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);
}
Luc-Olivier
  • 3,715
  • 2
  • 29
  • 29