Skip to content

Instantly share code, notes, and snippets.

@krhoyt
Created November 7, 2013 18:35
Show Gist options
  • Save krhoyt/7359597 to your computer and use it in GitHub Desktop.
Save krhoyt/7359597 to your computer and use it in GitHub Desktop.
Read a text file from disk.
- ( NSString * ) readTextFile : ( NSString * ) fileName
{
NSArray * directories;
NSData * buffer;
NSFileHandle * handle;
NSFileManager * manager;
NSMutableString * path;
NSString * contents;
manager = [NSFileManager defaultManager];
directories = NSSearchPathForDirectoriesInDomains( NSDesktopDirectory, NSUserDomainMask, YES );
path = [[NSMutableString alloc] initWithString : [directories objectAtIndex : 0]];
[path appendString: @"/"];
[path appendString: fileName];
// NSLog( @"%@", path );
if( [manager fileExistsAtPath : path] == NO )
{
NSLog( @"File not found." );
} else {
// NSLog( @"File exists." );
// Handle
handle = [NSFileHandle fileHandleForReadingAtPath : path];
// Read NSData
buffer = [handle readDataToEndOfFile];
// To string
contents = [[NSString alloc] initWithData : buffer encoding : NSUTF8StringEncoding];
// Log contents
NSLog( @"%@", contents );
// Close file
[handle closeFile];
}
return contents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment