2

I want get current file path,like in a.cpp,I can get

/home/workspace/src/a.cpp

How can I get this path?

Daniel Lee
  • 65
  • 1
  • 6

2 Answers2

7

You can use the standard macro __FILE__ to which expands to a string literal that contains the path of the current source file.

Starting from C++20, you can use default constructed std::source_location.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • This is what I want! – Daniel Lee May 11 '20 at 03:25
  • One more thing,if I want get /home/workspace,how should I use __FILE__? – Daniel Lee May 11 '20 at 03:30
  • I don't think there is any requirement that `__FILE__` contain a path? – M.M May 11 '20 at 03:30
  • @M.M To be exact *"The presumed name of the current source file"*. There's some discussion about it [here](https://stackoverflow.com/a/57548263/2079303). As far as I understand, implementation is quite free to provide anything it considers to be name of (what it considers to be) the file. In practice, compilers that I've used include a path in the name. – eerorika May 11 '20 at 03:42
0

I couldn't comment due to the reputation requirement.

But you might find this useful, a way to retrieve directory on Linux & Windows.

Hope this help!

mallocation
  • 526
  • 6
  • 13