0

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

有人可以告诉我如何使这项工作吗?提前致谢。

4

3 回答 3

4

这是一个方便的NSFileManager 类别,它获取和设置 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);
}
于 2015-03-20T07:08:46.733 回答
3

问题在于您对setxattr. sizeof通话无法使用。你要:

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

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

于 2013-05-06T15:11:16.817 回答
0

在此处阅读“获取和设置属性”部分。

对于您的示例,这是一些基本方法,也许会有所帮助:

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];
于 2013-05-06T14:08:56.590 回答