Problem using String Buffer Contents for opening up a FILE

In the following code a list of file names are stored in a String array, example 0.txt 1.txt etc.

I don't know why this line of code fails to open the SD file, myFile = SD.open(titlesbuffer[0]);
But this works myFile = SD.open("0.txt");

titlesbuffer[0] contains 0.txt based on the print statement.

Any ideas how to solve the problem? Thanks.

 SD.begin(5, SD_SCK_MHZ(12));                             
  titlesFile = SD.open("titles.txt");                     

  for (i = 0; titlesFile.available(); i++) {            
    titlesbuffer[i] = titlesFile.readStringUntil('\n');
  }
  titlesFile.close();  

  //---------------------------------------------

  Serial.println(titlesbuffer[0]);      // prints  0.txt
 
  SD.begin(5, SD_SCK_MHZ(12));    
  myFile = SD.open(titlesbuffer[0]);   // doesn't work
  //myFile = SD.open("0.txt");         //works

My best guess would be that the open() function cannot use an object of the String library as a parameter. Have you tried using C style strings, ie zero terminated arrays of chars instead ?

Try:
myFile = SD.open(titlesbuffer[0].c_str()); // doesn't work
That will give you a temporary character pointer that points to the contents of the String.

Thank you all for replying
The problem was that the text in the titlesbuffer included carriage returns and line feeds
Removing the Carriage Returns solved the problem
So myFile = SD.open(titlesbuffer[0]); WORKS NOW!

I thought that might be the problem. If the function wouldn't take a String argument you would have gotten a compile-time error.

instead of removing the Carriage Return is there a way to concatenate it with titlesbuffer like this

myFile = SD.open(titlesbuffer[0] + '\r' );

If you need to remove CR from the filenames to order to open files - what the purpose to add it?

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