Certainly! The original code snippet uses Windows API and some custom functions (Dir_BackSlashToSlash and Dir_upDir) to:
- Get the full path of the current executable.
- Convert backslashes (
\) to slashes (/).
- Move up one directory level.
Here is an equivalent implementation using standard C++17 or later (no Windows-specific API), using <filesystem> and standard string operations:
#include <iostream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
int main() {
// Get the path of the current executable
// Note: std::filesystem::current_path() gives the current working directory,
// but to get the executable path in a portable way, you need platform-specific code.
// For demonstration, let's assume current_path() is acceptable here.
fs::path exePath = fs::current_path(); // Replace with actual executable path if needed
// Convert backslashes to slashes (if any)
std::string pathStr = exePath.string();
for (auto& ch : pathStr) {
if (ch == '\\') ch = '/';
}
// Move up one directory
fs::path parentPath = fs::path(pathStr).parent_path();
std::cout << "Original path: " << pathStr << '\n';
std::cout << "Parent path: " << parentPath.string() << '\n';
return 0;
}
Notes:
-
Getting the executable path in standard C++ is not directly supported.
The Windows API function GetModuleFileNameA(nullptr, ...) returns the full path of the executable.
In portable C++, you typically cannot get the executable path without platform-specific code.
-
If you want a Windows-only solution but using C++ standard library for path manipulation, you can combine both:
#include <windows.h>
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
char sStartPath[MAX_PATH];
GetModuleFileNameA(nullptr, sStartPath, MAX_PATH);
fs::path exePath(sStartPath);
// Convert backslashes to slashes by using generic_string()
std::string pathStr = exePath.generic_string();
// Move up one directory
fs::path parentPath = exePath.parent_path();
std::cout << "Executable path: " << pathStr << '\n';
std::cout << "Parent directory: " << parentPath.generic_string() << '\n';
return 0;
}
-
fs::path::generic_string() returns the path with forward slashes (/), which replaces your Dir_BackSlashToSlash.
-
parent_path() is equivalent to your Dir_upDir.
If you want a fully portable way to get the executable path, you need platform-specific code for each OS (Windows, Linux, macOS). Let me know if you want that!