mr_georg mr_georg - 2 months ago 11
C Question

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

Mac OS X stores file creation time, and I know how to read it with

stat()
from
<sys/stat.h>
.

I could not find a way, how to set the creation time in C. It must be possible somehow, as the utility
SetFile
can do it (
SetFile
is part of the command line tools package from Apple):

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


How can I do it in C?

Answer

You can use utimes.

If times is non-NULL, it is assumed to point to an array of two timeval 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 (creation) times (such as UFS2), the birth time will be set to the value of the second element if the second element is older than the currently set birth time. To set both a birth time and a modification time, two calls are required; the first to set the birth time and the second to set the (presumably 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 modification time passed is older than the current creation time of the file, the creation time will be set. You can then call utimes again if you want to set a different modification time.