Not able to edit first byte of file using NSFileHandle

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?

Answers


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

Need Your Help

Validating post title and content in WordPress

php wordpress

I intend to let users create blog posts via the front end. I need to make sure the post title and content are each less than 100 characters.

Pass information to php file from javascript while restricting user from doing it their self?

php javascript ajax

I am making a game where the battle system uses javascript to battle. At the end of the battle you either win or lose. If the user wins, I need to update the mysql database with the XP they earne...