Re: Basic help with tab-delimited files
Re: Basic help with tab-delimited files
- Subject: Re: Basic help with tab-delimited files
- From: Douglas Davidson <email@hidden>
- Date: Wed, 30 Jan 2002 13:30:45 -0800
On Wednesday, January 30, 2002, at 12:01 PM, email@hidden wrote:
I am developing a Cocoa app that will need to open and process data
from a
tab-delimited text file. Anyone know of a well designed example of
doing
that? I see some Cocoa file related classes, but nothing that appears
to
handle what I need. I could write the code in C, but I'm not sure what
the
best method of integrating the two would be, or even if that would be
the
best option. Any pointers would be appreciated.
You could do something like this:
NSArray *contentsOfTabDelimitedFile(NSString *path) {
NSMutableArray *result = nil;
NSData *data = [NSData dataWithContentsOfFile:path];
if (data) {
NSString *string = [[[NSString alloc] initWith
Data:data
encoding:NSUTF8StringEncoding] autorelease];
if (string) {
unsigned idx = 0, length = [string length], start, end;
result = [NSMutableArray array];
while (idx < length) {
[string getLineStart:&start end:&idx contentsEnd:&end
forRange:NSMakeRange(idx, 0)];
[result addObject:[[string
substringWithRange:NSMakeRange(start, end - start)]
componentsSeparatedByString:@"\t"]];
}
}
}
return result;
}
Of course, there are a number of points that you would want to determine
for yourself. For example, what encoding does your file use? What do
you want to do if the file is not readable or not a text file in that
encoding? Do you want to read the file in whole or filemap it, or do
you want to read it a line at a time? Is it acceptable to copy the
contents, or do you need to process it in place? How do you want to
store the results?
This is a simple example that assumes the file is UTF8 (probably best
assumption at the BSD level on Mac OS X), reads it in whole and makes
copies (easiest for short files), stores the results as an NSArray of
NSArrays of NSStrings, and returns nil if the file cannot be read and
processed.
Douglas Davidson