sequential file names

02 Feb 2010

is there a way to code sequential file names?

 

For example I am currently using an SD card to datalog some files.  The file requires a very specialzed header file to export into another software for analysis.  Each time I power cycle the mbed it will write the file header.  This means that if there is an existing file with data the header will be written in the middle of the data stack.  This is a problem for parsing.

I was thinking something like... (not actual code just an idea)

If (file X exists),

then create file (X+n)

open file X+n

write to file X+n

 

Now this would get more complicated since I have a switch to enable datalogging.  Of course, the header has to write as the main loop initializes and the call function for the switch enabled datalog enables the loop after data collection.

02 Feb 2010

Here's an untested function for checking file existence. Hope it helps.

#include <mbed.h>

// return true if file (or directory) 'filename' is present in the directory 'root'
bool exists(char * root, char *filename)
{
    DIR *d = opendir(root);
    struct dirent *p;
    //printf("\nList of files in the directory %s:\n", root);
    bool found = false;
    if ( d != NULL )
    {
        while ( !found && (p = readdir(d)) != NULL )
        {
            //printf(" - %s\n", p->d_name);
            if ( strcmp(p->d_name, filename) == 0 )
                found = true;
        }
    }
    closedir(d);
    return found;
}

LocalFileSystem local("local");
int main( void )
{
    if ( exists("local", "myfile.txt") )
        printf ("Found myfile.txt\n");
    else
        printf ("Not found myfile.txt\n");
    return 0;
}

 

16 Jan 2012

Here's what I used successfully on one project; I used SDHCFilesystem (I forget where/which) / FATFileSystem (I forget where/which) but ... this should work fine on any filesystem that supports the basic operations. HTH

bool initLogfile() 
{    
    char myname[64];
    bool status = false;
    
    pc.printf("Opening log file...\n");

    while (fp == 0) {
        if ((fp = fopen("/log/test.txt", "w")) == 0) {
            pc.printf("Waiting for filesystem to come online...");
            wait(0.200);
        }
    }    
    fclose(fp);

    for (int i = 0; i < 1000; i++) {
        sprintf(myname, "/log/log%04d.csv", i);
        //pc.printf("Try file: <%s>\n", myname);    
        if ((fp = fopen(myname, "r")) == 0) {
            //pc.printf("File not found: <%s>\n", myname);
            break;
        } else {
            //pc.printf("File exists: <%s>\n", myname);
            fclose(fp);
        }
    }    
    
    fp = fopen(myname, "w");
    if (fp == 0) {
        pc.printf("file write failed: %s\n", myname);
    } else {
        //status = true;
        pc.printf("opened %s for writing\n", myname);
        status = true;
    }
    
    return status;
}