如何在Mac OS X下用C语言设置文件的创建日期?

Mac OS X存储文件创建时间,我知道如何使用 stat()读取它。

我找不到办法,如何在C中设置创建时间。必须有可能,因为实用工具SetFile可以做到这一点( SetFile是Apple命令行工具包的一部分):

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

我怎么能用C做呢?

你可以使用utimes 。

如果times为非NULL,则假定它指向两个timeval结构的数组。 访问时间设置为第一个元素的值,修改时间设置为第二个元素的值。

和:

对于支持文件出生(创建)时间的文件系统(例如UFS2),如果第二个元素早于当前设置的出生时间,则出生时间将设置为第二个元素的值。 要设置出生时间和修改时间,需要两次通话; 第一个设置出生时间,第二个设置(可能是更新的)修改时间

举个例子:

 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); 

如果传递的修改时间早于文件的当前创建时间,则将设置创建时间。 如果要设置不同的修改时间,则可以再次调用utimes

通过查看osxfuse loopback文件系统如何在此处实现设置创建时间: https : //github.com/osxfuse/filesystems/blob/master/filesystems-c/loopback/loopback.c

您似乎需要使用setattrlist(): https : //developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man2/setattrlist.2.html

似乎(来自loopback.c)代码将是这样的:

 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); 

其中“crtime”是struct timespec。 请参阅上面的man链接以获取必要的包含。

如果您阅读stat(2)手册页,则在SEE ALSO部分中引用utimes(2)。

 NAME futimes, utimes -- set file access and modification times LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include  int futimes(int fildes, const struct timeval times[2]); int utimes(const char *path, const struct timeval times[2]);