Generate unique file name on SD card

Hello, first time posting here...

I am trying to write files to an SD card (which I can already do just fine if I am only writing one specific file name) but I want to increment the file names each time I write a new file.

ie: 0.kml, 1.kml, 2.kml etc.

What I am trying to do is open the file (0.kml) then if I don't find it, this becomes the next file name. I am setting up a simple loop to look for the files in order, then, when it can't find a file with that name, it generate a new file. This is the code I am trying, but it gets stuck in my while loop.


  File kmlflightfile;
  int i = 0; //file name.
  boolean kmlfound = false; //mark true when file not found, vale of i then becomes file name.
  char FileName[13];

  while (kmlfound == false) {

    sprintf(FileName, "%i.kml", i);//set the file name
    Serial.println(FileName);
    kmlflightfile = SD.open(FileName);//look for this file name
    if (settings) {//you found this file try again
      i = i + 1;
      kmlflightfile.close();

    } else {
      kmlfound = true;
      kmlflightfile.close();
    }//you found the end of the file names, use the value of i as your new file name.

  }
  kmlflightfile = SD.open(FileName, FILE_WRITE);
  //if the file opened okay, write to it:
  if (kmlflightfile) {
    kmlflightfile.println("Did this work?");
    kmlflightfile.close();
  }else{
    Serial.print("Failed to write file");
  }
1 Like

You are testing the value of the settings variable but it does not appear to change in the snippet of code that you posted

1 Like

The variable settings is not defined anywhere in the code. It seems like that the variable is from example and you forgot to replace its name to the name of your file.

1 Like

Thanks guys! Yes, that was it! I copied this code from another section of my program that was working and missed changing that name "settings" to "kmlflightfile". It is working now!

I just needed a fresh set of eyes to catch my bug!

Thanks again!

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.