creat files in sd

Dependencies:   SDFileSystem mbed

Revision:
0:771b62e3ab62
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed May 06 10:46:46 2015 +0000
@@ -0,0 +1,122 @@
+#include "mbed.h"
+#include "SDFileSystem.h"
+#include <string>
+#include <vector>
+
+Serial pc(USBTX, USBRX);
+SDFileSystem sd(p5, p6, p7, p8, "sd"); // mosi, miso, sclk, cs, name
+Serial xbee(p13, p14);  // tx, rx
+DigitalOut rst1(p11);
+AnalogIn ain(p20);
+
+DigitalOut myled1(LED1);
+DigitalOut myled2(LED2);
+DigitalOut myled3(LED3);
+
+char fname[64];
+int i=0;
+vector<string> filenames; //filenames are stored in a vector string
+int fileNumber;
+
+
+int findNextFile()
+{
+
+    FILE *fp;
+    snprintf(fname,64,"/sd/mydir/myFile%04d.txt",fileNumber); // change to match your file name structure
+    fp = fopen(fname,"r");
+    while (fp) {
+        fclose(fp);
+        fileNumber++;
+        fp = fopen(fname,"r");
+    }
+
+    return fileNumber;
+}
+
+void read_file_names(char *dir)
+{
+    DIR *dp;
+    struct dirent *dirp;
+    dp = opendir(dir);
+    //read all directory and file names in current directory into filename vector
+    while((dirp = readdir(dp)) != NULL) {
+        filenames.push_back(string(dirp->d_name));
+    }
+    closedir(dp);
+}
+
+int main()
+{
+
+    myled1=1;
+    myled2=1;
+    wait_ms(20);
+
+
+
+    printf("if ther a directory of files in /sd/mydir\n");
+
+    DIR *d;
+    struct dirent *p;
+    char array[256];
+    d = opendir("/sd/mydir");
+
+    if (d == NULL) {
+        //error("Could not open  directory!");
+        mkdir("/sd/mydir", 0777);
+        printf(" create directory /sd/mydir");
+    } else {
+        while ((p = readdir(d)) != NULL) {
+            if ((strstr(p->d_name,".txt"))||(strstr(p->d_name,".txt"))) {
+                printf(" - %s\n\r", p->d_name);
+                printf("%s\n\r",array);
+            }
+
+        }
+    }
+
+    
+
+
+
+    // read file names into vector of strings
+    //read_file_names("/sd/mydir");
+    // pc.printf(" read_file_names \n\r");
+    //sprintf(filename, "/local/analog_%d.txt", x);
+    //i = findNextFile();
+    //FILE *fp = fopen(filename, "w");
+    //snprintf(fname, sizeof(fname), "/sd/mydir/sdtest%04d.txt", i);
+
+
+
+    FILE *fp = fopen("/sd/mydir/fname", "w");
+    if(fp == NULL) {
+        error("Could not open file for write\r\n");
+    }
+    pc.printf("File successfully opned and redy to use!\r\n");
+
+
+
+    myled1=0;
+    myled3=1;
+
+    for (int j=0; j<1000; j++) {
+        fprintf(fp, " Analog in = %d \n",ain.read_u16());
+        wait_ms(20);
+        myled2=0;
+    }
+
+    fclose(fp);
+    pc.printf(" close file\n\r");
+
+    while (1) {
+        myled2=0;
+        wait_ms(200);
+        myled2=1;
+        wait_ms(200);
+    }
+
+
+}
+