是否有任何 API 可以检查文件是否被锁定?我在类中找不到任何 API。NSFileManager
如果有任何 API 可以检查文件的锁定,请告诉我。
我找到了与文件锁定相关的以下链接
http://lists.apple.com/archives/cocoa-dev/2006/Nov/msg01399.html
我可以调用 – isWritableFileAtPath: on file。有没有其他方法可以查看文件是否被锁定?
是否有任何 API 可以检查文件是否被锁定?我在类中找不到任何 API。NSFileManager
如果有任何 API 可以检查文件的锁定,请告诉我。
我找到了与文件锁定相关的以下链接
http://lists.apple.com/archives/cocoa-dev/2006/Nov/msg01399.html
我可以调用 – isWritableFileAtPath: on file。有没有其他方法可以查看文件是否被锁定?
遵循代码对我有用。
NSError * error;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
BOOL isLocked = [[attributes objectForKey:NSFileImmutable] boolValue];
if (isLocked) {
NSLog(@"File is locked");
}
我真的不知道这个问题的答案,因为我不知道 OS X 如何实现其锁定机制。
它可能使用手册flock()
页中记录的 POSIX 咨询锁定,如果我是你,我会用 C 编写一个10 31 行的测试程序来显示fcntl()
(手册页)对您在 Finder 中所做的咨询锁定的看法。
类似(未经测试):
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
int main(int argc, const char **argv)
{
for (int i = 1; i < argc; i++)
{
const char *filename = argv[i];
int fd = open(filename, O_RDONLY);
if (fd >= 0)
{
struct flock flock;
if (fcntl(fd, F_GETLK, &flock) < 0)
{
fprintf(stderr, "Failed to get lock info for '%s': %s\n", filename, strerror(errno));
}
else
{
// Possibly print out other members of flock as well...
printf("l_type=%d\n", (int)flock.l_type);
}
close(fd);
}
else
{
fprintf(stderr, "Failed to open '%s': %s\n", filename, strerror(errno));
}
}
return 0;
}
如有必要,也可以使用 POSIX C 函数确定不可变标志(OS X '文件锁定')。不可变属性不是 unix 术语中的锁,而是文件标志。可以通过以下stat
函数获得:
struct stat buf;
stat("my/file/path", &buf);
if (0 != (buf.st_flags & UF_IMMUTABLE)) {
//is immutable
}
如需参考,请参阅:https ://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/stat.2.html
可以使用以下chflags
函数设置不可变标志:
chflags("my/file/path", UF_IMMUTABLE);