How to set file creation date in C under Mac OS X?

Mac OS X stores the file creation time, and I know how to read it using stat() from <sys/stat.h> .

I could not find a way to set the creation time in C. This should be possible somehow, as the SetFile utility can do ( SetFile is part of Apple's command-line tool package):

 SetFile -d '12/31/1999 23:59:59' file.txt 

How can I do this in C?

+6
source share
3 answers

You can use utimes .

If the time is not NULL, it is assumed that it points to an array of two time intervals of structures. The access time is set to the value of the first element, and the modification time is set to the value of the second element.

and

For file systems that support file birth time (creation) (for example, UFS2), the time of birth will be set to the value of the second element if the second element is older than the current time of birth. Set both birth time and modification time, two calls are required; the first to set the time of birth and the second to set the (supposedly newer) modification time

As an example:

 struct timeval times[2]; memset(times, 0, sizeof(times)); times[0].seconds = 946684799; /* 31 Dec 1999 23:59:59 */ times[1].seconds = 946684799; utimes("/path/to/file", &times); 

If the elapsed modification time is outdated than the current file creation time, the creation time will be set. You can call utimes again if you want to set a different modification time.

+3
source

Seeing how the osxfuse loopback file system implements creation time settings here: https://github.com/osxfuse/filesystems/blob/master/filesystems-c/loopback/loopback.c

It seems you need to use setattrlist (): https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man2/setattrlist.2.html

It seems (from loopback.c) the code will be along the lines of:

 struct attrlist attributes; attributes.bitmapcount = ATTR_BIT_MAP_COUNT; attributes.reserved = 0; attributes.commonattr = ATTR_CMN_CRTIME; attributes.dirattr = 0; attributes.fileattr = 0; attributes.forkattr = 0; attributes.volattr = 0; res = setattrlist(path, &attributes, &crtime, sizeof(struct timespec), FSOPT_NOFOLLOW); 

Where "crtime" is a struct timespec. See the human link above for necessary inclusions.

+1
source

If you are reading the stat (2) man page, this applies to the scraps (2) in the SEE ALSO section.

 NAME futimes, utimes -- set file access and modification times LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <sys/time.h> int futimes(int fildes, const struct timeval times[2]); int utimes(const char *path, const struct timeval times[2]); 
0
source

All Articles