user698200
user698200

Reputation: 399

How do I change C file operation to Objective C?

char buf[32];

FILE *fp = fopen("test.txt", "r");

fscanf(fp, "%s", buf);

fclose(fp);

I want to change above C file operations to Objective-C.

How do I change?

Is not there fscanf kind of thing in Objective-C?

Upvotes: 0

Views: 426

Answers (3)

Abizern
Abizern

Reputation: 150565

You just want to read a text file into a string?

NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:@"test.txt" withEncoding:NSUTF8StringEncoding error:&error];

if(!fileContents) {
    NSLog(@"Couldn't read file because of error: %@", [error localizedFailureReason]);
}

This assumes UTF8 encoding, of course.

Upvotes: 1

Micah Hainline
Micah Hainline

Reputation: 14417

Your best bet is to use NSData to read in your file, and then create a string from that.

NSData *dataContents = [NSData dataWithContentsOfFile: @"test.txt"];
NSString *stringContents = [[NSString alloc] initWithData: dataContents 
                                       encoding: NSUTF8StringEncoding];

Assuming your file is UTF8.

No sense messing around with buffers. Let the framework do the dirty work.

EDIT: Responding to your comment, if you really, truly need to read it line by line, check out Objective-C: Reading a file line by line

Upvotes: 2

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

You don't. You can't scan from FILE * directly into an NSString. However, once you've read into the buffer, you can create an NSString from it:

NSString *str = [NSString stringWithCString: buf encoding: NSASCIIStringEncoding]; // or whatever

NOTE, however, that using fscanf as you have here will cause a buffer overflow. You must specify the size of the buffer, minus one for the trailing null character:

fscanf(fp, "%31s", buf);

Upvotes: 2

Related Questions