6

How does one read a data file in an iPhone project? For example, lets say I have a static file called "level.dat" that is structured as follows: obstacles: 10 time: 100 obstacle1: 10,20 ...

I would like to read the contents of the file into a NSString then do the parsing. How do I read the contents of a file into a string? Also, where in the project should the "level.dat" file reside? Should it be under "Resources" or just in the main directory?

Thanks in advance!

Chris Hanson
  • 52,684
  • 8
  • 70
  • 102
user21293
  • 6,331
  • 10
  • 41
  • 57

4 Answers4

18

See this answer: How to fopen() on the iPhone? which shows how to get access to resources in your bundle. Once you have the path, just use [NSString stringWithContentsOfFile:encoding:error:].

NSString   *path = [[NSBundle mainBundle] pathForResource: @"level" ofType: @"dat"]
NSError    *error = nil;
NSString   *data = [NSString stringWithContentsOfFile: path 
                                             encoding: NSUTF8StringEncoding 
                                                error: &error];
Community
  • 1
  • 1
Ben Gottlieb
  • 84,498
  • 22
  • 171
  • 170
3

While this isn't what you asked for, consider turning your files into plists. You will have to reformat them into XML, but then you can load them straight into a NSDictionary with:

dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"levels" ofType:@"plist"]];
Chris Jefferson
  • 7,133
  • 9
  • 35
  • 59
0

Have you considered putting the data in an SQLite database instead of a flat file? I find that the API is very easy to use on the iPhone.

It is how I do all of my data storage on the phone now.

Lee
  • 741
  • 5
  • 2
-1

If you need help parsing the data string, there's a helpful article on Cocoa For Scientist

Dan
  • 1,675
  • 1
  • 21
  • 35