Trouble opening file with SD.open(String FileName, FILE_WRITE);

Hello all,

I'm trying something unique, trying to open a file on SD Card by String variable instead of predetermined text but it isn't quite working.

I'm reading a string from Serial coming over from a computer to create a filename in text, then trying to open that file on sd card using the variable.

Currently, the project isn't building but here is what I'm trying:

Char Data = '';
String FileName = '';

//then I listen for chars in a loop until char == \n to build the filename with:

Data = Serial.read();

Filename += Data

//then after building the FileName, I try to open it with:

SD.open(FileName, FILE_READ);

// But the IDE is giving error saying:

No Matching Function for Call to SDClass::open(String&, Const uint8_t&)

I declared a String called FileName. Does it not know what a String variable is or is it expecting predetermined text?

I'm trying to transfer files from PC to the SD Card through the Arduino because I don't have a micro sd adapter so I'm going to have to do everything in a sort of binary or char mode.

Help would be appreciated, thanks!

Resolved. The IDE isn't as advanced as I thought it would be.

Simply put, we can not use String data-types to specify a String-based File-name to use with SD.open.

The Filename has to be a char array for some reason.

It would make more sense to be able to use String datatypes when handing text to any object.

It would make more sense to be able to use String datatypes when handing text to any object.

Classes like String are great for PCs, phones, and tablets where there is lots of memory.

It would be better to never use String on Arduino. String is a major cause of problems on Arduino because of fragmentation of the heap by String.

This type failure is very common for programs that use files since about 700 bytes is required for the SD block cache and other file system data. Most programs use Serial so half of RAM is used for SD and Serial on an Uno. String silently fails when the heap is fragmented and there is less than 128 bytes of free stack. Sometimes programs just mysteriously crash because the stack overlaps the heap.

The use of classes like String is forbidden in embedded systems for critical applications and the use of dynamic memory prevents certification of software. See the ISO 26262 and MISRA standards for automotive embedded systems. Other standards have similar restrictions for Aerospace and medical devices.

Safe String like classes can be implemented for embedded systems but this will never happen for Arduoino.

You can easily use String in open.

#include <SD.h>
void setup() {
  // other code

  // ...

  String filename = "test.txt";
  file = SD.open(filename.c_str(), FILE_WRITE);
}

void loop() {}
1 Like