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