# Reading a text file in Objective-C



## Viro (Jun 28, 2005)

I'm trying to figure out how I would read a text file, line by line in Objective-C. I've looked at NSFile, but I think that is for dealing with binary files. There isn't corresponding NSTextFile or something that looks like it deals with text files.

What is the usual way of dealing with text files? Do you just use NSString's methods like initWithContentsOfFile and stringWithContentsOfFile? These methods are only available on 10.4 and later. What options do you have if you aren't using 10.4?


----------



## Mikuro (Jun 28, 2005)

I use NSData's dataWithContentsOfFile, and then pass that to NSString's initWithData:encoding. That way will work pre-Tiger. I guess that would be a bit inefficient with large files, since you'd be duplicating the entire contents of the file in memory, but it gets the job done, anyway.


----------



## Viro (Jun 28, 2005)

Thanks for the info. It doesn't sound too efficient, but I guess that will have to do. I'm just glad my files don't exceed 100 MB in size.


----------



## lurk (Jun 28, 2005)

Actually IIRC large files are not read into memory.  They are mmap-ed and faulted in as need be.  That is part of the reason NSData is a class cluster, to support optimizations like that one.


----------



## Captain Code (Jun 28, 2005)

What about NSString's initWithContentsOfFile(I think)?  I came across this and it couldn't be easier.  Does anyone know if this has the same optimizations if the file is large?


----------



## Viro (Jun 29, 2005)

That method is only available in Tiger and later versions of OS X. I mentioned in the original post and was interested to see if there were other ways that weren't tiger specific.


----------

