Read Text file Programmatically using Objective-C

后端 未结 2 791
慢半拍i
慢半拍i 2020-12-07 14:47

I am new to iPhone Programming

I want to read the content of text file which is in my Resourse folder. i did a lot of googling but failed to get proper way for doing

2条回答
  •  星月不相逢
    2020-12-07 15:05

    The first thing you want to do is get the path for the text file you want to read. Since it's in your Resources folder, I'm assuming you're copying it into the main bundle of the application. You can get the path for a file in your main bundle using NSBundle's pathForResource:ofType:

    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *filePath = [mainBundle pathForResource:@"filename" ofType:@"txt"];

    Then you can read the file at that path into an NSString directly using initWithContentsOfFile:usedEncoding:error:

    NSStringEncoding encoding;
    NSError *error;
    NSString *fileContents = [[[NSString alloc] initWithContentsOfFile:filePath
                                                          usedEncoding:&encoding
                                                                 error:&error]
                              autorelease];

提交回复
热议问题