Maxime
Maxime

Reputation: 3165

Seek to file position in Objective-C

What it's the equivalent in Objective-C of this C code:

FILE* file = fopen( [filePath UTF8String], "r, ccs=UTF-8");
if (file != 0)
{
    char buffer[1024];
    //seek to file position....
    fseek(file,11093, SEEK_CUR);
    int cnt = 0;
    while(fgets(buffer, 1024, file) != NULL)
    {   
        if (cnt>0) {
            if(buffer[0] == 'a') {
                break;
            }
            //Objective c syntax....
            NSString *string = [[NSString alloc] initWithCString: buffer];
         }
        cnt++;
    }
    fclose(file);
}

Upvotes: 0

Views: 1891

Answers (1)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

That is the equivalent. Objective-C is built on top of C, so every C function is usable in Objective-C.

There is a class hierarchy rooted at NSStream which, at first glance, may appear to be the Objective-C version of file streams--and for many uses, it is. But if you need to seek through an arbitrary stream, you'll want to keep using fopen(), fseek(), etc.

An instance of NSInputStream created from a path to a file on disk will be seekable by getting/setting its NSStreamFileCurrentOffsetKey property. However, it's often awkward to adapt existing FILE *-based code.

I guess what I'm saying is that if fopen() works for you, there's no need to stop using it. :)

Upvotes: 3

Related Questions