views:

51

answers:

1

I am using the following code to open a file's contents and save it to another file. when it runs the original file length is 793 but the saved file is 0. I have also tried just to copy the file. Nothing seems to work.

Is there some kind of permissions I'm missing on the documents directory?

NSError *error;
    NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* nGram = [basePath stringByAppendingPathComponent:@"contacts.gram"];
NSString *oGram = [basePath stringByAppendingPathComponent:@"/../vText.app/model/lm/TAR9230/contacts.gram"];
      NSString *gramString = [[NSString alloc] initWithContentsOfFile:oGram  encoding:NSUTF8StringEncoding error:&error];
      BOOL ok = [gramString writeToFile:nGram atomically:NO encoding:NSUnicodeStringEncoding error:&error];
      if(!ok) NSLog(@"Mayday!");
      NSLog(@"%d",[gramString length]);
      gramString = [[NSString alloc] initWithContentsOfFile:nGram  encoding:NSUTF8StringEncoding error:&error];
      NSLog(@"%d",[gramString length]);
+1  A: 

This entire block is unnecessary. All you need is:

NSString *fp=[[NSBundle mainBundle] pathForResource:@"contacts" ofType:@"gram"];
NSString *gramString = [[NSString alloc] initWithContentsOfFile:fp  
                                                       encoding:NSUTF8StringEncoding 
                                                          error:&error];

You certainly don't want to try to directly access a file in the app bundle using a hardcoded path because the file isn't guaranteed to be in the same exact place in every build.

In the code you do have, you want to use the same encoding constant for reading as you did for writing. You write with NSUnicodeStringEncoding but you read with NSUTF8StringEncoding. These should overlap but why take the chance if you know the exact coding used?

TechZen
that was the problem; NSUnicodeStringEncoding => NSUTF8StringEncoding; some how I missed that, thank you so much.
Kungfurabbits
on a side note, is the pathForResource recursive? from your code it appears it is. thanks again.
Kungfurabbits
Yes it will find a resource in the app bundle regardless of were it is. You can use `pathForResource:ofType:inDirectory:` or related methods to narrow things down if you want.
TechZen