10 years, 5 months ago.

creating a non-existing file on a SD-card

Hello! I've encountered a problem with my code. I'm trying to locate a filename not already in use on the SD-card and then create that name. My code looks like this at the moment:

code

char fileName[] = "/sd/mydir/LOGGER00.CSV";
int main() {
    printf("Hello World!\n");   
 
  //  mkdir("/sd/mydir", 0777);
    for(uint8_t i = 0; i<100; i++){
        fileName[17] = i/10 + '0';
        fileName[18] = i%10 + '0';
        FILE *fp = fopen(fileName, "w" );
        printf(fileName,".txt");
        printf("\n");
        if(fp == NULL) {
            printf("Could not open file for write\n");
            mkdir(fileName, 0777);
            FILE *fp = fopen(fileName, "w" );
        }// if
        if(fp != NULL){
            printf("File opened at: %c", fileName);
            break;
            }// if

    }// for
    fprintf(fp, "Hello fun SD Card World!");
    fclose(fp); 
 
    printf("Goodbye World!\n");
}

it's based upon a Arduino way of using the Adafruit Data Logging Shield and the example code from Mbed. My problem is the "." (dot) in fileName is not saved as a dot, but as a "0" (zero). Is there any workaround this problem?

1 Answer

10 years, 5 months ago.

Yes, the workaround is to count better :P

If I am not mistaken it should be number 16 and 17 in the filename you need to change, not 17 and 18.

Accepted Answer

That would certainly help but isn't the biggest problem.

If say you are trying to locate an unused file and then create that file. Your current code will always overwrite the first file on the sd card.

    mkdir("/sd/mydir", 0777); // don't comment this out, you want to ensure the directory exists.
    FILE *fp; // declare this outside of the loop not each time around it.

    for(uint8_t i = 0; i<100; i++){
        fileName[16] = i/10 + '0';    // arrays count from 0 so the number is 16 and 17
        fileName[17] = i%10 + '0';
        fp = fopen(fileName, "r" ); // open as read not write, write will overwrite the current file.
        printf(fileName);                // no .txt, the file isn't .txt
        printf("\n");

        if(fp == NULL) {
            // read failed so file doesn't exist.            
            fp = fopen(fileName, "w" ); // open as read not write
            
            if(fp != NULL){                                           // check we opened it for writing.
              printf("File opened at: %s\n", fileName); // %s not %c, this is a string not a char
              break;
            } else {
              printf("Failed to open %s for read or write access. Check card is inserted.\n", fileName);
            }

        } else {
          fclose(fp); // fp not null, we opened the file read only, close before trying the next name.
        }
    }// for

    fprintf(fp, "Hello fun SD Card World!");
    fclose(fp); 

posted by Andy A 10 Jun 2014