我希望能够获得当前的源文件路径。
string txt_file = CURRENT_FILE_PATH +"../../txt_files/first.txt";
inFile.open(txt_file .c_str());
Run Code Online (Sandbox Code Playgroud)
有没有办法获得 CURRENT_FILE_PATH ?我不是说可执行路径。我的意思是运行代码的源文件的当前位置。
非常感谢,乔拉。
用于编译源文件的路径可通过标准 C 宏访问__FILE__(请参阅http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html)
如果您将绝对路径作为编译器的输入(至少对于 gcc)__FILE__将保存文件的绝对路径,反之亦然。其他编译器可能略有不同。
如果您使用 GNU Make 并且在变量中列出源文件,SOURCE_FILES如下所示:
SOURCE_FILES := src/file1.cpp src/file2.cpp ...
Run Code Online (Sandbox Code Playgroud)
您可以确保文件由其绝对路径给出,如下所示:
SOURCE_FILES := $(abspath src/file1.cpp src/file2.cpp ...)
Run Code Online (Sandbox Code Playgroud)
C++20 source_location::file_name
除了__FILE__不使用旧的 C 预处理器之外,我们现在还有另一种方法:http : //www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf
文档只是说:
constexpr const char* file_name() const noexcept;
5 返回: 由该对象表示为 NTBS 的当前源文件 (14.2) 的假定名称。
其中 NTBS 表示“空终止字节字符串”。
当支持到达 GCC 时,我会尝试一下,GCC 9.1.0g++-9 -std=c++2a仍然不支持它。
https://en.cppreference.com/w/cpp/utility/source_location声明用法如下:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int main() {
log("Hello world!");
}
Run Code Online (Sandbox Code Playgroud)
可能的输出:
info:main.cpp:16:main Hello world!
Run Code Online (Sandbox Code Playgroud)