Sunday 12 July 2009

Reading a raw datafile

To open a file and read its data first you need to get the path to the file.

    NSBundle* bundle = [NSBundle mainBundle];

    NSString* documentsDirectory = [bundle resourcePath];

    

    NSString *path = [documentsDirectory stringByAppendingString:@"/GBPUSD5.csv"];


documentsDirectory will hold the path to the resources folder of our application. I have chucked the GBPUSD5.csv file into there. Then I get the whole path by appending the filename GBPUSD5.csv to it. Note I have had to put the / in as well..

We open the file :


    NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path];


and can jump to any position in the file :

    [file seekToFileOffset:0];


Then we can read the data we need :

        NSData *record = [file readDataOfLength:48];

        NSString* aStr = [[NSString alloc] initWithData:record encoding:NSASCIIStringEncoding];


aStr contains the data as a string that we can get down and boogy with!

1 comment:

  1. A slight aside, but it seems if you want to view the contents of the entire path variable in the xCode debugger, it will truncate it and will not show the entire string.

    Annoying.

    To view the whole thing, which may be useful at times, open up the debugger console and type :

    po path

    This will show the entire path variable.

    ReplyDelete