Hello. I want to check a received string and open a corresponding binary file from a SD card. Like this
if (strcmp(receivedString, "one") == 0) myFile = SD.open("one.bin");
if (strcmp(receivedString, "two ") == 0) myFile = SD.open("two.bin");
and so on, 50 times. The way I have done it works, but it is very memory hungry. I am sure there is a more elegant and more economical way of doing it, but it's beyond me. Any suggestions?
strlcpy and strlcat are safer methods to use as they protect you against buffer overflows if the destination is too small
See strlcpy_strlcat.ino for an example sketch
These will not crash you code if the result is too long , and you can easily check for errors
char filename[30];
if (strlcpy(filename, receivedString, sizeof(filename)) > sizeof(filename)) {
// increase filename
Serial.println(F(" filename size too small"));
}
if (strlcat(filename, ".bin", sizeof(filename)) > sizeof(filename)) {
// increase filename
Serial.println(F(" filename size too small"));
}
Edit - corrected strncpy to strlcpy etc while snprintf is the 'safe' version of sprintf, just to be confusing strncpy is NOT the safe version of strcpy
Edit - fixed order of args in strlcpy strlcat
no memory fragmenation
Edit @PieterP correctly points out due to the memory allocation in SD,open there will be a memory hole when String filename disposed of
thanks @PieterP