是否有任何API來檢查文件是否被鎖定?我無法在NSFileManager
類中找到任何API。讓我知道是否有任何API檢查文件的鎖定。如何檢查文件是否鎖定在Cocoa中?
,我發現文件鎖定
http://lists.apple.com/archives/cocoa-dev/2006/Nov/msg01399.html
我可以調用相關的以下鏈接 - isWritableFileAtPath:對文件。有沒有其他的方法來查找文件是否被鎖定?
是否有任何API來檢查文件是否被鎖定?我無法在NSFileManager
類中找到任何API。讓我知道是否有任何API檢查文件的鎖定。如何檢查文件是否鎖定在Cocoa中?
,我發現文件鎖定
http://lists.apple.com/archives/cocoa-dev/2006/Nov/msg01399.html
我可以調用相關的以下鏈接 - isWritableFileAtPath:對文件。有沒有其他的方法來查找文件是否被鎖定?
下面的代碼爲我工作。
NSError * error;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
BOOL isLocked = [[attributes objectForKey:@"NSFileImmutable"] boolValue];
if(isLocked)
{
NSLog(@"File is locked");
}
+1很高興知道! – trojanfoe 2012-07-31 12:18:23
我真的不知道這個問題的答案,因爲我不知道OS X如何實現其鎖定機制。
它可能使用POSIX建議鎖定爲記錄在flock()
manpage,如果我是你,我會寫在C 31行的測試程序來展示一下fcntl()
(manpage)認爲有關的諮詢鎖你從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;
}
OS X文件鎖/不可變是一個文件標誌(請參閱我的回答) – codingFriend1 2012-10-29 10:12:09
關於trojanfoe未經測試的代碼,它現在已經過測試:)並且發現需要多一行。在調用fcntl之前,你需要告訴它你正在尋找什麼樣的鎖。通常,使用 flock.l_type = F_WRLCK; 其中F_WRLCK表示尋找Read或Write(又名Exclusive)鎖。 – 2015-01-09 16:47:04
如有必要,還可以使用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);
參考文獻見:https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man2/chflags.2.html
什麼樣的鎖定? POSIX鎖定或更高級別(我不知道名稱)? – trojanfoe 2012-07-31 10:17:51
@trojanfoe:我不太確定鎖定。可能是POSIX。我使用finder鎖定了文件。我想檢查我的應用程序中鎖定的文件。 – Ram 2012-07-31 10:24:43