Search code examples
iphonensstringnsrange

Get ranged string from text file without opening file with stringWithContentsOfFile


I'm trying read text from text file. I used stringWithContentsOfFile to do this.

pathName        = [[NSBundle mainBundle] pathForResource:sample ofType:@"txt"];
entireContent   = [NSString stringWithContentsOfFile:pathName encoding:NSUTF8StringEncoding error:NULL];
entireChapter   = [entireContent substringWithRange:sourceRange];

Have any of you got another way to get string fast?


Solution

  • you can use NSFileHandle.

    NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [fileHandler seekToFileOffset:10];
    NSData *data = [fileHandler readDataOfLength:10];
    [fileHandler closeFile];
    

    you can try this. then you can convert nsdata to string.