1

在我的应用程序中,我正在使用 NSFileHandle 编辑一些文件,但它没有被编辑。

下面是代码:带有注释和日志输出

    //Initialize file manager
    NSFileManager *filemgr;
    filemgr = [NSFileManager defaultManager];

    //Initialize file handle
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];

    //Check if file is writable
    if ([filemgr isWritableFileAtPath:filePath]  == YES)
        NSLog (@"File is writable");
    else
        NSLog (@"File is read only");

    //Read 1st byte of file
    NSData *decryptData = [fileHandle readDataOfLength:1];

    //Print first byte & length
    NSLog(@"data1: %d %@",[decryptData length],decryptData);   //data2: 1 <37>

    //Replace 1st byte
    NSData *zeroData = 0;
    [fileHandle writeData:zeroData];

    //Read 1st byte to check
    decryptData = [fileHandle readDataOfLength:1];

    //Print first byte
    NSLog(@"data2: %d %@",[decryptData length],decryptData);  //data2: 1 <00>

    NSURL *fileUrl=[NSURL fileURLWithPath:filePath];
    NSLog(@"fileUrl:%@",fileUrl);

    [fileHandle closeFile];

有什么建议么?

4

1 回答 1

3

如果要使用写入NSFileHandle,则需要打开文件进行写入和读取:

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];

如果您不确定指定路径中的文件是否可写,则应在打开它之前检查适当的权限,如果权限不足以满足您的需要,则向用户显示错误。

此外,要写入数据,您需要创建一个NSData. 代码行

NSData *zeroData = 0;

正在创建一个nil对象,而不是一个包含零字节的对象。我想你想要

int8_t zero = 0;
NSData *zeroData = [NSData dataWithBytes:&zero length:1];
于 2012-06-14T11:35:09.960 回答