Write to SDHC file sysem

13 Apr 2011

Hello I want to write/read data to a file on an SDHC card and I adapted a program SDHCFileSystem. I cant seem to open or create a file.Can anyone shed any light on this please ?

<<code>>

  1. include "mbed.h"
  2. include "string"
  3. include "SDHCFileSystem.h"
  4. define MAXLINE 100 Serial pc(USBTX, USBRX); tx, rx char myline [MAXLINE]; SDFileSystem sd(p5, p6, p7, p8, "sd"); mosi, miso, sclk, cs

int main() { pc.printf("\n\rIn the main program"); FILE *fp; fp = fopen("/myfile.txt", "w+"); if(fp==NULL) { pc.printf("File not created or opened"); } else { fprintf(fp, "\n\rHello World!\n\r"); fscanf(fp,"%s",&myline); just reads the first word 'Hello' pc.printf("\n\rRead from SD card file: \"%s\"",myline); fclose(fp); }

}

<</code>>

13 Apr 2011

For some reason your formatting didn't work. Here's the fixed ver.

#include "mbed.h"
#include "string"
#include "SDHCFileSystem.h"
#define MAXLINE 100
Serial pc(USBTX, USBRX); // tx, rx
char myline [MAXLINE];
SDFileSystem sd(p5, p6, p7, p8, "sd"); // mosi, miso, sclk, cs
   
int main()
{
       pc.printf("\n\rIn the main program");
       FILE *fp;
       fp = fopen("/myfile.txt", "w+");
       if(fp==NULL)
       {
       pc.printf("File not created or opened");
       }
       else
       {
       fprintf(fp, "\n\rHello World!\n\r");
       fscanf(fp,"%s",&myline); // just reads the first word 'Hello'
      pc.printf("\n\rRead from SD card file: \"%s\"",myline);
       fclose(fp);
       }
       
}

Since you declared SDFileSystem to be in "sd" namespace (last parameter in the constructor), you need to use it in the file name: fp = fopen("/sd/myfile.txt", "w+");

13 Apr 2011

Thanks for your interest however it still doesn't work and seems to get stuck on "if(fp==NULL)" and tells me the file is not created. Despite this it does continue and report some information about the card so I assume it can see the card but not write to it.

"In the main program Init: SDCARD_V2. init_card=2. CSD_STRUCT = 0. SDCard. c_size: 0EA7. capacity: 1967128576. sectors: 3842048".

13 Apr 2011

Does it make any difference it you open with "w", or "a" instead of "w+"?

14 Apr 2011

I'vebtried all these parameters without success

10 Nov 2013

w+ and a+ works, You have just to write text and terminate by "\r\n" not "\n". If you use \n it juste back return to the same line and dont create new !