Random read/write to SD card?

07 May 2011

Does SDFileSystem and SDHCFileSystem support r+ (and w+) for opening a file for random read/writes? I need to seek all over the file to do database operations, so append isn't going to work for me.

Here is my code that is failing at the first fopen. Each time the program run it is supposed to swap the two ints in order in the file. Similar code works in cygwin, doesn't work in mbed.

#include <mbed.h>
#include "SDHCFileSystem.h"

#define DEBUG_LINE printf("%d\n", __LINE__);

Serial console(USBTX, USBRX);

void exitmsg(const char* message)
{
   fprintf(stderr, "%s\n", message);
   exit(1);
}

int main()
{
    SDFileSystem sd(p5, p6, p7, p8, "sd"); // mosi, miso, sclk, cs, mount point

    console.baud(921600); // mbed to pc usb serial supports: 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, 230400, 460800, 921600

    console.puts(
        "\x1b[2J\x1b[H"
        __FILE__ "\r\n"
        __DATE__ " " __TIME__ "\r\n"
        "\r\n");

DEBUG_LINE
   FILE* fp = fopen("/sd/ttt.bin", "r+");
DEBUG_LINE   
   if (fp == 0)
   {
DEBUG_LINE   
      fp = fopen("/sd/ttt.bin", "w+");
   }
DEBUG_LINE

   fseek(fp, 0, SEEK_END);
   int size = ftell(fp);
   printf("size = %d\n", size);

   int data1=0;
   int data2=0;

   if (size == 0)
   {
      data1=123;
      if (fwrite(&data1, sizeof(data1), 1, fp) != 1)
         exitmsg("failed to write");
      data2=321;
      if (fwrite(&data2, sizeof(data2), 1, fp) != 1)
         exitmsg("failed to write");
   }

   data1 = 0;
   data2 = 0;
   fseek(fp, 0, SEEK_SET);
   if (fread(&data1, sizeof(data1), 1, fp) != 1)
      exitmsg("failed to read");
   if (fread(&data2, sizeof(data2), 1, fp) != 1)
      exitmsg("failed to read");

   fseek(fp, 0, SEEK_SET);
   if (fwrite(&data2, sizeof(data2), 1, fp) != 1)
      exitmsg("failed to write");
   if (fwrite(&data1, sizeof(data1), 1, fp) != 1)
      exitmsg("failed to write");

   printf("read: %d %d\n", data1, data2);
   printf("wrote: %d %d\n", data2, data1);

   fclose(fp);
}
07 May 2011

Look at the FatFs here: http://elm-chan.org/fsw/ff/00index_e.html
The f_lseek can be the answer.
There is a Mbed adaptation : http://mbed.org/users/emh203/programs/CHAN_FATFS/lktgi7

I hope this can help you...but i did not yet test it !
Robert

08 May 2011

Good news! I got a USB thumb drive (SD in USB adapter) to work. I will investigate other alternatives too. Thanks!

http://mbed.org/users/igorsk/notebook/interfacing-usb-mass-storage-devices-aka-usb-flash/