Read and write file in iPhone

2019-03-16 22:00发布

问题:

How to make file read/write operation on iPhone?which is the path i need to specify to save the file? how can i get the current working directory in iPhone?

Thank You

回答1:

Write to a file:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

// the path to write file
NSString *myFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];

[data writeToFile:myFile atomically:YES];

Read a file:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];  
NSData *myData = [NSData dataWithContentsOfFile:filePath];  
if (myData) {  
    // do something useful  
}