Pages

Monday, March 1, 2010

Objective-C. Read text file.

This small program reads the text file:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString* fileName = @"text.txt";
NSString *fileString = [NSString stringWithContentsOfFile: fileName];

NSArray *lines = [fileString componentsSeparatedByString:@"\n"];

[pool drain];
return 0;
}

How to make this program:
1. Launch Xcode
2. Menu File -> New Project -> Command Line -> Foundation Tool.
3. Put this program into main.m file.

The text file should be near the executable file. The text will be in fileString.

Of course, the standard C will work too:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
char buffer[1024];
FILE* file = fopen("text.txt", "r");
if (file != 0)
{
while(fgets(buffer, 1024, file) != NULL)
{
NSString* string = [[NSString alloc] initWithCString: buffer];
NSLog(string);
[string release];
}
fclose(file);
}
[pool drain];
return 0;
}

No comments:

Post a Comment