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?

asked Nov 11, 2021 at 14:40
2
  • 1
    Did you choose 9600 baud in the serial monitor? Commented Nov 11, 2021 at 14:43
  • 1
    Yes this was on 9600 Commented Nov 11, 2021 at 14:44

1 Answer 1

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.

answered Nov 11, 2021 at 15:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.