I am writing a C++ code and I want to print the current filename with its extension. Yes, it's one of the frequently asked questions. One solution is to use argv[0]. It is cool, but it's not giving the extension. Can I have it with the extension?
You can print the full path name using std::cout << __FILE__
.
If you want to print the file name alone, then you can do:
std::string file = __FILE__;
size_t index;
for (index = file.size(); index > 0; index--)
{
if (file[index - 1] == '\\' || file[index - 1] == '/')
break;
}
std::cout << file.substr(index);
Which platform are you on. Following program
#include <iostream>
int main(int argc, char* argv[])
{
std::cout << "Name: " << argv[0] << std::endl;
}
Works perfectly for me on debian (gcc), windows (msvc and mingw gcc)
> a.exe
Name: a.exe
> a
Name: a
$ ./a.out
Name: ./a.out
It actually contains command used to start the program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With