Not able to edit first byte of file using NSFileHandle

依然范特西╮ 提交于 2019-12-11 11:09:46

问题


In my app, I am using NSFileHandle to edit some file but it is not editing.

Below is the code: with comments & logs output

    //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];

Any Suggestions?


回答1:


If you want to write using NSFileHandle you need to open the file for writing as well as reading:

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];

If you aren't sure if the file at the specified path is writable, you should check for the appropriate permissions before you open it and display an error to the user if they are insufficient for what you need to do.

Also, to write data you need to create an instance of NSData. The line of code

NSData *zeroData = 0;

is creating a nil object, not an object containing a zero byte. I think you want

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


来源:https://stackoverflow.com/questions/11032027/not-able-to-edit-first-byte-of-file-using-nsfilehandle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!