revolutionkpi
revolutionkpi

Reputation: 2682

Append binary data to file

in my iPhone application I need to append binary data to file:

 NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];

    NSData* data = [NSData dataWithBytes:buffer length:readBytes_];    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];

    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
    [myHandle seekToEndOfFile];
    [myHandle writeData: data];
    [myHandle closeFile];
   // [data writeToFile:appFile atomically:YES];

    // Show contents of Documents directory
    NSLog(@"Documents directory: %@",
          [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

But in NSlog i don't see that there is my file. What is wrong?

Upvotes: 3

Views: 2378

Answers (1)

trojanfoe
trojanfoe

Reputation: 122401

If the files does not exist then [NSFileHandle fileHandleForUpdatingAtPath:] will return nil (see the docs).

Therefore check that before attempting to open the file and create it if necessary:

NSFileManager *fileMan = [NSFileManager defaultManager];
if (![fileMan fileExistsAtPath:appFile])
{
    [fileMan createFileAtPath:appFile contents:nil attributes:nil];
}
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
// etc.

And add more error-checking all round.

Upvotes: 3

Related Questions