Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing current file name with extension in C++

Tags:

c++

file

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?

like image 479
froghramar Avatar asked Apr 01 '16 11:04

froghramar


2 Answers

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);
like image 192
barak manos Avatar answered Oct 23 '22 05:10

barak manos


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.

like image 27
Zereges Avatar answered Oct 23 '22 05:10

Zereges