在VS中定位当前工程项目的根目录!
涉及到:
#include <windows.h>头文件中的GetCurrentDirectory()方法和GetModuleFileName()方法。
file_manager.h
#pragma once #include <windows.h> #include <string> using namespace std; class FileManager { public: static string GetRootDirectory(); static string GetExeDirectory(); private: //构造函数 FileManager() {}; //获取当前项目根目录 static void loadRootDir(); //获取exe文件目录 static void loadExeDir(); //静态数组 static char rootPath[MAX_PATH]; //根目录 static char exePath[MAX_PATH]; //执行文件目录 }; file_manager.cpp #include "file_manager.h" //类的静态数组 初始化 char FileManager::rootPath[MAX_PATH] = ""; char FileManager::exePath[MAX_PATH] = ""; string FileManager::GetRootDirectory() { loadRootDir(); string root = rootPath; /* for (char &c : root) { if (c == '\\') c = '\/'; }*/ for (auto iter = root.begin(); iter != root.end(); iter++) { if (*iter == '\\') *iter = '\/'; } return root; } string FileManager::GetExeDirectory() { loadExeDir(); string exe = exePath; exe = exe.substr(0, exe.find_last_of('\\')); /* for (char &c : exe) { if (c == '\\') c = '\/'; }*/ for (auto iter = exe.begin(); iter != exe.end(); iter++) { if (*iter == '\\') *iter = '\/'; } return exe; } //获取当前项目根目录 void FileManager::loadRootDir() { GetCurrentDirectory(MAX_PATH, rootPath); } //获取exe文件目录 void FileManager::loadExeDir() { GetModuleFileName(NULL, exePath, MAX_PATH); } 使用方法: //获取当前项目目录 string rootPath = FileManager::GetRootDirectory(); std::cout << "root: " << rootPath << std::endl; //获取exe文件的目录 string exePath = FileManager::GetExeDirectory(); std::cout << "exe: " << exePath << std::endl;