SD card open and close

Dependencies:   mbed 4180-L2-P13

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "SDFileSystem.h"
00003  
00004 SDFileSystem sd(p5, p6, p7, p8, "sd"); // the pinout on the mbed Cool Components workshop board
00005 Serial          pc(USBTX, USBRX);
00006 LocalFileSystem chip("uc");\
00007  
00008 int main() {
00009     FILE * pFile;
00010     long lSize;
00011     char * buffer;
00012     size_t result;
00013     
00014     printf("Hello World!\n");   
00015  
00016     mkdir("/sd/mydir", 0777);
00017     
00018     FILE *fp = fopen("/sd/mydir/sdtest.txt", "w");
00019     if(fp == NULL) {
00020         error("Could not open file for write\n");
00021     }
00022     fprintf(fp, "Hello SD File World!");
00023     fclose(fp); 
00024  
00025     printf("Goodbye World!\n");
00026     
00027     pFile = fopen("/sd/mydir/sdtest.txt", "r"); 
00028     if (pFile==NULL) {
00029         fputs ("File error",stderr);
00030         exit (1);
00031     }
00032     // obtain file size:
00033     fseek (pFile , 0 , SEEK_END);
00034     lSize = ftell (pFile);
00035     rewind (pFile);
00036     pc.printf("File Size: %d\n",lSize);
00037     
00038     buffer = (char*) malloc (sizeof(char)*lSize);
00039     if (buffer == NULL) {
00040         fputs ("Memory error",stderr);
00041         exit (2);
00042     }
00043     
00044     // copy the file into the buffer:
00045     result = fread (buffer,1,lSize,pFile);
00046     if (result != lSize) {
00047         fputs ("Reading error",stderr);
00048         exit (3);
00049     }
00050     pc.printf("%s",buffer);
00051     /* the whole file is now loaded in the memory buffer. */
00052     fclose (pFile);
00053     free (buffer);
00054     return 0;
00055     
00056     
00057 }