Saturday, November 8, 2014

MAC OS app - reading contents from a file

Since the file reading operations will take good amount of time, It is good idea to start that in a separate thread


[NSThread detachNewThreadSelector:@selector(scanAndFindLocationChangeReports:) toTarget:self withObject:absString];


-(void) scanAndFindLocationChangeReports:(NSString*) filePath
{
    const char* filePathCStr = [filePath cStringUsingEncoding:NSUTF8StringEncoding];
    FILE *file = fopen(filePathCStr, "r");
    // check for NULL
    while(!feof(file))
    {
        NSString *line = readLineAsNSString(file);
        // do stuff with line; line is autoreleased, so you should NOT release it (unless you also retain it beforehand)
        NSLog(@"-- File Line is :%@",line);
    }
    fclose(file);
    [self performSelectorOnMainThread:@selector(updateLabels) withObject:nil waitUntilDone:NO];
}


NSString *readLineAsNSString(FILE *file)
{
    char buffer[4096];
    
    // tune this capacity to your liking -- larger buffer sizes will be faster, but
    // use more memory
    NSMutableString *result = [NSMutableString stringWithCapacity:256];
    
    // Read up to 4095 non-newline characters, then read and discard the newline
    int charsRead;
    do
    {
        if(fscanf(file, "%4095[^\n]%n%*c", buffer, &charsRead) == 1)
            [result appendFormat:@"%s", buffer];
        else
            break;
    } while(charsRead == 4095);
    
    return result;
}

No comments:

Post a Comment