写扩展文件属性

时间:2013-05-06 13:55:18

标签: ios objective-c

我正在尝试使用以下代码在文件头中写入一些数据(数据长度为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);

有人能告诉我如何才能完成这项工作?提前谢谢。

3 个答案:

答案 0 :(得分:3)

问题在于您致电setxattr。无法使用sizeof来电。你想要:

int result = setxattr(path, attrName, myDataBytes, [myData length], 0, 0);

sizeof(myDataBytes)的调用将返回指针的大小,而不是数据的长度。

答案 1 :(得分:1)

这是一个方便的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);
}

答案 2 :(得分:0)

阅读“获取和设置属性”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];