0
我正在用C++創建一個遊戲引擎,並且我已經開始添加對加載文件的支持。我創建了一個看起來像這樣的負載文件的方法:C++ - 你如何獲得C++可執行文件的當前目錄?
#include <string>
#include <fstream>
std::string read_file(const char* filepath) {
FILE* file = fopen(filepath, "rt");
if(file != NULL) {
fseek(file, 0, SEEK_END);
} else {
std::string error_message = std::string("[ERROR]: Failed to load file ");
error_message.append(filepath);
return error_message;
}
unsigned long length = ftell(file);
char* data = new char[length + 1];
memset(data, 0, length + 1);
fseek(file, 0, SEEK_SET);
fread(data, 1, length, file);
fclose(file);
std::string result(data);
delete[] data;
return result;
}
爲了測試這個功能,我決定嘗試加載「的test.txt」的文件,但是這不會工作,除非我包括完整路徑,例如
"/Users/(Username)/.../(Executable Directory)/text.txt"
,而不是僅僅
"test.txt"
因此,要解決這個問題,我需要一種方式來獲得的可執行文件所在的目錄的完整路徑,然後追加文件名稱到結束的路徑,並加載我的加載文件方法。
任何人都知道如何獲得路徑?
不是名爲'find_executable()'的函數嗎? –
@RavenH .:找到可執行文件的函數叫做'find_executable'。要獲取包含它的目錄,可以調用'find_executable'返回的路徑上的'parent_path()'。 –