Reputation: 3713
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?
Upvotes: 7
Views: 1783
Reputation: 277
By looking how osxfuse loopback filesystem implements setting creation time here: https://github.com/osxfuse/filesystems/blob/master/filesystems-c/loopback/loopback.c
It seems that you need to use setattrlist(): https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man2/setattrlist.2.html
Seems (from the loopback.c) the code would 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 struct timespec. See the man link above for the necessary includes.
Upvotes: 3
Reputation: 16728
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", ×);
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.
Upvotes: 4
Reputation: 155
If you read the stat(2) man-page, it refers to utimes(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]);
Upvotes: 0