0

I want to extract the file name MyFile.txt out of a path which is stored in a string "C:\\MyDirectory\\MyFile.txt";

I found a simple c code which does the job.

string filename = "C:\\MyDirectory\\MyFile.bat";

// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.find_last_of("\\/");
if (std::string::npos != last_slash_idx)
{
    filename.erase(0, last_slash_idx + 1);
}

// Remove extension if present.
const size_t period_idx = filename.rfind('.');
if (std::string::npos != period_idx)
{
    filename.erase(period_idx);
}

I had to alter few things for arduino code example replace find_last_of with lastIndexOf, erase with remove and rfind with lastIndexOf

Here the ino file

#include<string>
void setup() {
  Serial.begin(9600);

}

void loop() {   
   String filename = "C:\MyDirectory\MyFile.bat";

// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.lastIndexOf("\\");
if (std::string::npos != last_slash_idx)
{
    filename.remove(0, last_slash_idx + 1);
}

// Remove extension if present.
const size_t period_idx = filename.lastIndexOf('.');
if (std::string::npos != period_idx)
{
    filename.remove(period_idx);
}  
Serial.println(filename);
delay(1000);
}

Expected output MyFile

When I look into Serial Monitor I get

c$$⸮'<;⸮⸮/<⸮⸮$⸮''⸮;,#$$⸮'<;⸮⸮'<⸮⸮$⸮''⸮:$#$$⸮'<;⸮⸮'<⸮⸮$⸮''⸮;$#$$⸮'

What am I doing wrong?

1 Answers1

1
#include<string>

Remove this. Arduino uses its own String class, different from the STL string.

String filename = "C:\MyDirectory\MyFile.bat";

There is no '\M' escape sequence in C++ strings. You probably mean "C:\\MyDirectory\\MyFile.bat".

const size_t last_slash_idx = filename.lastIndexOf("\\");

String::lastIndexOf() returns an int, not size_t.

if (std::string::npos != last_slash_idx)

No std::string here. String::lastIndexOf() returns -1 to signify that the character was not found.

With all these fixes, your sketch should work as intended.

Edgar Bonet
  • 39,449
  • 4
  • 36
  • 72