Problem with the C++

03 Mar 2010

I am writing a few pieces of code for opening a couple of files in the SD card. But there is something wrong with that bold code below which could not be compiled.

int n;
    
    while(1){
        n=n+1;
        FILE *fp = fopen("/sd/%d.txt", "w", n);
        if(fp == NULL) {
            error("Could not open file for write\n");
        }
Does anyone know how to correct the code so that I can open many files in the SD card?

03 Mar 2010

It should be:

    FILE *fp = fopen("/sd/d.txt", "w");
04 Mar 2010

Hi,

I think the OP wants to programmatically open a series of files on the card in which case the following code should work (not tested).

int n;
char buff[16];
    
    while(1){
        n=n+1;
        sprintf(buff,"//sd//%d.txt", n);
        FILE *fp = fopen(buff, "w");
        if(fp == NULL) {
            error("Could not open file for write\n");
        }
05 Mar 2010

Thanks, that works well. But the result is not what I want. It opens the files automatelly, which is not expected. I am expecting to open a file once I press the reset button. Would you mind giving some suggestions after having looked through the following code?

 

#include "mbed.h"
#include "SDFileSystem.h"

AnalogIn xin(p20);
AnalogIn yin(p19);

SDFileSystem sd(p5, p6, p7, p13, "sd");

int main() {
    float xval;
    float yval;
    int loop=0;
    //int n=0;
    //char fileName[10];//Give us room for a file name upto 10 characters long
    
    //while(1){
        //n=n+1;
        //sprintf(fileName, "/sd/%d.txt", n);
        //FILE *fp = fopen(fileName, "w");
    FILE *fp = fopen("/sd/foo.txt", "w");
    if(fp == NULL) {
        error("Could not open file for write\n");
    }

        while(1){
        loop=loop+1;
        xval=xin.read();
        yval=yin.read();
        fprintf(fp, "x: %f, y: %f\r\n", xval, yval);
        if (loop>=10000) break;
    }        
        fclose(fp);
        
        //if (n>=100) break;
}