简体   繁体   English

在Cocoa中设置符号链接的修改日期

[英]Set modification date on symbolic link in Cocoa

In Cocoa, I would like to set the modification date of a symbolic link. 在Cocoa中,我想设置符号链接的修改日期。

Using the [NSFileManager setAttributes:ofItemAtPath:error:] works well with regular files but not with symbolic links. 使用[NSFileManager setAttributes:ofItemAtPath:error:]可以很好地处理常规文件,但不能使用符号链接。

How can I achieve that? 我怎样才能做到这一点?

There is no way to do it directly with NSFileManager. 没有办法直接使用NSFileManager。 The setAttributes:ofItemAtPath:error: method wraps up a bunch of BSD path-based functions like utimes, setxattr, chown, etc., all of which follow symlinks instead of operating on them directly. setAttributes:ofItemAtPath:error:方法包装了一堆基于BSD路径的函数,如utimes,setxattr,chown等,所有这些函数都遵循符号链接,而不是直接对它们进行操作。

One obvious alternative is to drop down to the BSD layer manually. 一个明显的选择是手动下拉到BSD层。 Some of the functions have "don't follow symlinks" versions, like lchown, but not all of them do. 有些函数有“不遵循符号链接”的版本,比如lchown,但并非所有版本都有。 In particular, the one that changes the mod time, utimes, does not. 特别是,改变mod时间的那个,utimes,却没有。 So you have to open the file and use the fd-based variant, futimes. 所以你必须打开文件并使用基于fd的变体,futimes。 Here's what the code would look like: 这是代码的样子:

int fd = open([NSFileManager fileSystemRepresentationWithPath:path], O_RDONLY | O_SYMLINK);
futimes(fd, 0);
close(fd);

If you plan to do a lot of this, you can write your own setAttributes:ofSymlinkAtPath:error: implementation in a category on NSFileManager that wraps up futimes, fchflags, fsetxattr, etc. 如果你计划做很多这样的事情,你可以编写自己的setAttributes:ofSymlinkAtPath:error:在NSFileManager上的一个类别中实现包含futimes,fchflags,fsetxattr等。

The only real problem with this is that you need to have read access to the symlink itself (as well as whatever access you need to modify the mod time, etc.) for this to work, but that's usually not a problem, and as far as I know OS X has no way around it anyway. 唯一真正的问题是你需要对符号链接本身具有读访问权限(以及修改模式时间所需的任何访问权限等)才能使其工作,但这通常不是问题,并且到目前为止据我所知,OS X无论如何都无法绕过它。 (Linux does let you open a file for neither read nor write access, just to do f* calls, but BSD does not.) (Linux确实允许你打开一个既不读取也不写入的文件,只是为了进行f *调用,但是BSD没有。)

As another alternative, I believe the NSURL file URL APIs do not follow symlinks, which means this should work (but I'm not in front of my Mac right now, so I can't test): 作为另一种选择,我相信NSURL文件URL API 遵循符号链接,这意味着它应该工作(但我现在不在我的Mac前面,所以我无法测试):

[[NSURL fileURLWithPath:path isDirectory:NO] setResourceValue:[NSDate date] forKey:NSURLContentModificationDateKey error:nil];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM