63

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 this task.

Please suggest

Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
Rupesh
  • 7,866
  • 11
  • 41
  • 58

2 Answers2

157

The files in your "Resource folder" are actually the contents of your application bundle. So first you need to get the path of the file within your application bundle.

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

Then loading the content into a NSString is even easier.

NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];

As a bonus you can have different localized versions of filename.txt and this code will fetch the file of the currently selected language correctly.

PeyloW
  • 36,742
  • 12
  • 80
  • 99
  • The encoding doesn't works for all the files. If you create a text file in Windows having euro symbol in it with ANSI encoding then euro symbol will be converted to someother symbol using above code. Is there any generic way to support all the character set using single encoding. – Arun Gupta Apr 01 '15 at 17:23
8

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];
Tim
  • 59,527
  • 19
  • 156
  • 165