-->

不能编辑使用NSFileHandle文件的第一个字节(Not able to edit first

2019-10-16 20:57发布

在我的应用程序,我使用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];

有什么建议么?

Answer 1:

如果你想用写NSFileHandle你需要打开文件进行写入和读:

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];

如果你不能确定是否在指定的路径中的文件是可写的,你应该检查相应的权限,你打开它,并显示错误给用户,如果他们是不够的,你需要做什么之前。

此外,将数据写入您需要创建的实例NSData 。 代码行

NSData *zeroData = 0;

是创建一个nil对象,而不是含一个零字节对象。 我想你想

int8_t zero = 0;
NSData *zeroData = [NSData dataWithBytes:&zero length:1];


文章来源: Not able to edit first byte of file using NSFileHandle