10 years, 5 months ago.

Problem while reading a file

Hi! I'm trying to read a .txt file from mbed but i'm unable to see anything from the TeraTerm terminal window. Here is my sample code for reading a file.. I've already created the sample.txt in mbed and it has characters inside.. Cheers,

Reading from file

#include "mbed.h"
Serial pc(USBTX, USBRX);

int main() {

    int c;
    FILE *file;
    file = fopen("sample.txt", "r");
    
    if (file) {
        while ((c = getc(file)) != EOF)
            pc.putc(c);
        fclose(file);
    }
}

3 Answers

10 years, 5 months ago.

try this, will read UP-TO 64 chars, (can be changed), pushes result into an array of char ..

    char buffer [128];

    ..

    ..


    bool ret =  (fgets(buffer, 64, fp)) ;
    
    if (ret)
    {
        pc.printf ("I read a line of text for you, ... \"%s\" \r\n", buffer);
    }

Hope that works for you,

Ceri

Accepted Answer

Thanks it works well now, just added the line below between char buffer and bool ret lines..

FILE *fp = fopen("/local/out.txt", "r");

posted by Vedat A 13 Nov 2013
10 years, 5 months ago.

You should use the code for the ''LocalFileSystem'' as described in the handbook:

#include "mbed.h"
 
LocalFileSystem local("local");               // Create the local filesystem under the name "local"
 
int main() {
    FILE *fp = fopen("/local/out.txt", "w");  // Open "out.txt" on the local file system for writing
    fprintf(fp, "Hello World!");
    fclose(fp);
}

Vedat A
poster
10 years, 5 months ago.

Writing to a file works fine, but my purpose is to read the contents of the file and see them from the terminal. Btw, I forgot the line LocalFileSystem local("local") but after I added it, the problem still exits..

Still then you should look at that code, especially fopen: You need to give the full path when opening it, not only the file name.

posted by Erik - 12 Nov 2013

Yyeah, I missed to put it's directory..Thanks

Cheers,

posted by Vedat A 13 Nov 2013