Send sketch filename to Serial Monitor

I came across this line to output the full directory + file name of the sketch:

Serial.printlin(__FILE__);

Works like a beauty, but is there a way to output the sketch filename only (without the preceding directory string)?

TIA

1 Like

…so you walk backwards through the string looking for the last backslash.

Or last regular slash if using a Mac...

... well yes I can write code to slice the string up, but I was hoping for something simpler builtin, like:

Serial.println(__FILENAME__);   // doesn't work !

:grinning:

:face_with_spiral_eyes:

Try __FILE_NAME__

from:

no luck ... won't compile, darn!

tried __BASE_FILE__ too, but it outputs another directory string :upside_down_face:

PS: thanks for the \ hint van_der_decken, or is that van\_der\_decken :slightly_smiling_face:

If you put backslashes before the underscores, Markdown will output literal underscores, i.e., entering \_\_BASE_FILE\_\_ displays __BASE_FILE__

There's a whole swack of different answers to this question in this stackoverflow topic. Some even work!

One of the Q&D'ier solutions goes like this:

#include <string.h>

void setup() {
   Serial.begin(115200);
   delay(2000);
   Serial.println(strrchr("/" __FILE__, '/') + 1);
}

void loop() {
}
1 Like

LOL! With a char array string, find the terminating 0 and while backward to the first \ and return a pointer to the next char. The code needs to know the buffer length and color inside the lines.

You can use string.h functions but try array-walking some time, it's about as fast and does not #include that library.

But maybe you do want to use string.h!
The function names look arcane but those are abbreviated words like str for string and cmp for compare jammed together and there's only so many of those. But I prefer to roll my own.

Arduino Standard C Libraries source and docs site.

If you want to check syntax, the Reference is the door.
The Libraries Reference page with links to the Library docs.

Thanks van_der_decken (again) . The most popular solution from that linked stackoverflow discussion works a treat (using \\ for windows):

#define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
.
.
Serial.println(__FILENAME__)

although I decided to define simply FILENAME not __FILENAME__ in my sketch

Or use back-ticks: __FILE__

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.