0

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?

Chirag Kothiya
  • 955
  • 5
  • 12
  • 28
user698200
  • 399
  • 1
  • 7
  • 19
  • For what it's worth, you can keep this code if you want to. Objective-C is a superset of C, and all the POSIX file stuff is available. See @Micah's answer for the equivalent, though. – Ben Zotto Jun 03 '11 at 20:43
  • I know Objective-C is a superset of C. But I have to change buf to NSString to do something. Do I have to use [NSString stringWithCString...] after each fscanf? – user698200 Jun 03 '11 at 20:54

3 Answers3

2

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);
Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
2

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

Community
  • 1
  • 1
Micah Hainline
  • 14,367
  • 9
  • 52
  • 85
  • I want to do something while I read file line by line. I don't want do that after I read to the end of file. How can I do that? – user698200 Jun 03 '11 at 20:46
1

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.

Abizern
  • 146,289
  • 39
  • 203
  • 257
  • I simplified my code too much. There are a lot of stuffs between fopen and fclose. I have to change buf to NSString right after I read line. I don't want to do that after I read whole file. – user698200 Jun 04 '11 at 14:28