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

时间:2015-11-07 19:41:50

标签: c macos

Mac OS X存储文件创建时间,我知道如何使用stat()中的<sys/stat.h>来阅读它。

我找不到方法,如何在C中设置创建时间。必须以某种方式实现,因为实用程序SetFile可以做到(SetFile是命令行工具包的一部分来自Apple):

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

我怎样才能在C中完成?

3 个答案:

答案 0 :(得分:3)

您可以使用utimes

  

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

  

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

举个例子:

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

答案 1 :(得分:1)

通过查看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链接以获取必要的包含。

答案 2 :(得分:0)

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

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