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?
9600