写扩展的文件属性
我尝试写一些数据(该数据的长度为367字节)使用下面的代码在文件的标题:写扩展的文件属性
const char *attrName = [kAttributeForKey UTF8String];
const char *path = [filePath fileSystemRepresentation];
const uint8_t *myDataBytes = (const uint8_t*)[myData bytes];
int result = setxattr(path, attrName, myDataBytes, sizeof(myDataBytes), 0, 0);
当我尝试读它时,结果是不同的:
const char *attrName = [kAttributeForKey UTF8String];
const char *path = [filePath fileSystemRepresentation];
int bufferLength = getxattr(path, attrName, NULL, 0, 0, 0);
char *buffer = malloc(bufferLength);
getxattr(path, attrName, buffer, bufferLength, 0, 0);
NSData *myData = [[NSData alloc] initWithBytes:buffer length:bufferLength];
free(buffer);
有人能告诉我怎么做这项工作?提前致谢。
问题是与您的来电setxattr
。 sizeof
呼叫不能使用。你想:
int result = setxattr(path, attrName, myDataBytes, [myData length], 0, 0);
到sizeof(myDataBytes)
的调用将返回指针的大小,数据的不长。
非常感谢 – Levi 2013-05-06 15:30:47
阅读“获取和设置属性”部分here。
对于这里的例子是一些基本的方法,也许它会帮助:
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *path;
/*
* You can set the following attributes: NSFileBusy, NSFileCreationDate,
NSFileExtensionHidden, NSFileGroupOwnerAccountID, NSFileGroupOwnerAccountName,
NSFileHFSCreatorCode, NSFileHFSTypeCode, NSFileImmutable, NSFileModificationDate,
NSFileOwnerAccountID, NSFileOwnerAccountName, NSFilePosixPermissions
*/
[fm setAttributes:@{ NSFileOwnerAccountName : @"name" } ofItemAtPath:path error:nil];
感谢您的答案,不幸的是我无法弄清楚如何设置自定义属性。任何想法? – Levi 2013-05-06 14:42:34
这不是用于自定义属性,而是用于预定义属性 – 2016-02-19 14:01:20
这是一个方便的NSFileManager category,它获取并设置NSString作为文件的扩展属性。
+ (NSString *)xattrStringValueForKey:(NSString *)key atURL:(NSURL *)URL
{
NSString *value = nil;
const char *keyName = key.UTF8String;
const char *filePath = URL.fileSystemRepresentation;
ssize_t bufferSize = getxattr(filePath, keyName, NULL, 0, 0, 0);
if (bufferSize != -1) {
char *buffer = malloc(bufferSize+1);
if (buffer) {
getxattr(filePath, keyName, buffer, bufferSize, 0, 0);
buffer[bufferSize] = '\0';
value = [NSString stringWithUTF8String:buffer];
free(buffer);
}
}
return value;
}
+ (BOOL)setXAttrStringValue:(NSString *)value forKey:(NSString *)key atURL:(NSURL *)URL
{
int failed = setxattr(URL.fileSystemRepresentation, key.UTF8String, value.UTF8String, value.length, 0, 0);
return (failed == 0);
}
那么,对于初学者来说,人为地限制你的getter为255字节。如果你的数据更长,它会被截断 - 你已经mallocing正确的大小缓冲区来保存它,为什么不通过bufferLength传递给'getxattr'? – 2013-05-06 13:59:41
@BenZotto谢谢,我改变了它。还要别的吗? – Levi 2013-05-06 14:05:52
只是为了防止任何人需要它:这是一个Swift包装获取,设置,列出和删除扩展属性:http://stackoverflow.com/questions/38343186/write-extend-file-attributes-swift-example。 – 2016-10-12 08:36:18