views:

101

answers:

2

Hi all,

I am trying to perform the following tasks with files, but I am stuck.

Here is the code:

NSString* aStr = @"Hello World!";

NSData* aData;
aData = [aStr dataUsingEncoding: NSASCIIStringEncoding];

NSFileManager *fileManager = [NSFileManager defaultManager];

//destination is NSString which Contains the absolute address

if ([fileManager fileExistsAtPath:destination]) 
{
      NSLog(@"File Exists!");
}
else
{
     BOOL statusOfFile=[fileManager createFileAtPath :destination contents:aData attributes:nil];
}

if(statusOfFile)
     printf("\n\nFile Created!");
else
     printf("\n\nError in File creation!");


I am not able to able to create a file - the value of statusOfFile is NO.

I tried this code in GNU and it works fine - the problem exists only with Xcode.

Can anybody tell me why?

Can anybody help? Thanks.

+1  A: 

To access and store files on the iPhone I recommend reading this.

Erica Sadun has also written a nice shorty about accessing file within a app bundle.

epatel
Thank you epatel
socialCircus
+6  A: 

It is possible that your destination is an invalid path on the iPhone. If you want to be able to write to a file in your apps sandboxed "Documents" folder, try this code:

+ (NSString *)dataFilePath {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                       NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *filename = [documentsDirectory stringByAppendingPathComponent:@"Filename.plist"];

  return filename;
}

@end
Benny Wong
thanks alot @bdotdub but m trying to create a txt file .so if i change the extension will it work?
socialCircus
Yes, the parameter for stringByAppendingPathComponent can be anything.
Benny Wong
Thanks a lot Benny Wong!!
socialCircus