how to read a file from documents directory

2019-08-23 11:02发布

i hav to read the file with name myname.plist from documents directory .....i want to store the content of the file to string....

1条回答
可以哭但决不认输i
2楼-- · 2019-08-23 11:16

Something like this should do:

/* Find the documents directory. */
NSArray *paths = NSSearchPathForDirectoriesInDomains(
        NSDocumentsDirectory, NSUserDomainMask, YES/*expand tilde*/);
NSAssert([paths count] > 0,
         @"%s: No user document directory found!", __func__);
NSString *documentsDir = [paths objectAtIndex:0U];

/* Build the file path. */
NSString *name = [@"myname" stringByAppendingPathExtension:"plist"];
NSString *path = [documentsDir stringByAppendingPathComponent:name];

/* Read in the file content. */
NSError *error = nil;
NSStringEncoding enc;
NSString *content = [NSString
                     stringWithContentsOfFile:path
                     usedEncoding:&enc
                     error:&error];
if (!content) {
    NSLog(@"%s: Error reading content of \"%@\": %@", __func__, path, error);
}
查看更多
登录 后发表回答