localFileSystem and reading files

20 Jul 2012

So, from what I can tell from searching the forums, etc....most people are interested in writing stuff to the localfilesystem... I am trying to find some information on reading a text file from the localfilesystem..

In particular, I'm trying to figure out how to tell how many lines there are in a text file... or at least how to read through them all sequentially.. So far, I have the code below (generic example from the only stuff I could find so far)... which allows me to sift through a number of lines in the text file and print it... But, I can't seem to find anything like a 'do while not eof' kind of thing that will loop through until it hits the end of the file...

#include "mbed.h"
 
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);

LocalFileSystem local("local");
Serial pc(USBTX, USBRX);

int main() {
    led2 = 1;
    pc.baud(921600);
    printf("File Parsing:\n");
    
    wait(5.0);
    FILE *fp = fopen( "/local/textfile.txt", "r");
    printf("\nLoading file:\n");
    led1 = 1;
    if ( fp == NULL ) {
        error("Could not open file for read operation.\n");
    }
    char buf[256];
    for (int n=45; n>0; n--) {
        fgets(buf, sizeof(buf), fp);
            printf("%s", buf);
    }

    wait(5.0); 
    printf("Closing File...\n");
    fclose(fp);
 
        // Drive should be restored. this is the same as just returning from main
 
        wait(5);
}

If anyone has a suggestion, I'd love to hear it!