Thanks for your responses.

Looks like stringWithContentsOfFile:encoding:error:  does what I need.

Jens, at least I know not to pursue the NSScanner thing any further in this case.

Thanks,

Ian.


On 23/07/2008, at 3:39 AM, Jens Alfke wrote:


On 22 Jul '08, at 2:09 AM, Ian Jackson wrote:

NSString *path = ...;
NSData *data = [NSData dataWithContentsOfFile:path];
// assuming data is in UTF8
NSString *string = [NSString stringWithUTF8String:[data bytes]];

The reason this doesn't work is that -stringWithUTF8String: expects a NUL-terminated C string, but [data bytes] just returns the raw contents of the data block. So the string factory method will keep reading past the end of the data until it finds a zero byte in whatever happens to be randomly out there. That means it'll read garbage past the end of the string, and if that garbage doesn't look like valid UTF-8, it'll fail.

The correct call to make would be
        [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]
although as Patrick already replied, the best way to read a string from a file is +stringWithContentsOfFile:usedEncoding:error:, which will attempt to determine the encoding.

However, the files also include identifiers such as "usemtl", which could appear at any time. So any ideas how you go about searching for a set of characters, and a set of strings simultaneously? i.e. how do I search for the characters without momentarily ignoring the strings or vice versa? This seems to be quite straightforward with fscanf, but it seems a bit odd going to C, when I'm trying to do this in Objective-C.

This is beyond what NSScanner can do. You have a number of options, like scanning the string character by character using a 'for' loop, using a parser generator like ANTLR, or simply calling fscanf. (There's nothing wrong with using C APIs, when appropriate.)

—Jens

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to