Go Down

Topic: Using a variable file name? (Read 2109 times) previous topic - next topic


I have 10 files on the SD card 1.txt 2.txt 3.txt on up to 10.txt…

I want to have a variable I can increment in a loop that will count up such as:

// set up the variable to be used
Int FileToOpen = 1;

void loop() {

myFile = SD.open(FileToOpen + ".txt");

// Do some reading of the file

// increment the file number to be opend


I get errors like cant use an int with a string/char and so on…

Any ideas of how to do this???

Thanks for any help!!!


Jun 01, 2012, 08:15 pm Last Edit: Jun 01, 2012, 08:24 pm by Erni Reason: 1
I asked same question here:


As you se the solution was to use sprintf() something like

sprintf(newfile, "%0d.txt", FileToOpen); (your filenames should be 01.txt .. 10.txt)


This might help, it is a function taken from my MIDI wave shield sample player. It generates a file name with a number only it uses .wav in place of the .txt that you want.
It builds up the name in an char array which is then passed to the file opening routine.

Code: [Select]

        char toPlay[11];     //  string array for file to play 00.WAV to 99999.WAV

void makeName(int number, int depth){  // generates a file name 0.WAV to 9999.WAV suppressing leading zeros
  if(number > 9) {
    makeName(number / 10, ++depth); // recursion
    number = number % 10;   // only have to deal with the next significant digit of the number
  toPlay[indexToWrite] = (number & 0xf) | 0x30;
  if(depth > 0) {return; } // return if we have more levels of recursion to go
  else {  // finish off the string with the wave extesion
  toPlay[indexToWrite] = '.';
  toPlay[1+indexToWrite] = 'W';
  toPlay[2+indexToWrite] = 'A';
  toPlay[3+indexToWrite] = 'V';
  toPlay[4+indexToWrite] = '\0'; // terminator
  indexToWrite = 0; // reset pointer for next time we enter

Go Up