When creating a file in the current directory where the program is executing, it's crucial to obtain the correct path. However, in your code, you encounter an exception during GetCurrentDirectory().
The exception is likely caused by an invalid argument passed to GetCurrentDirectory. You need to allocate a buffer to store the directory path before calling this function.
To retrieve the path of the executable file, consider using GetModuleFileName instead:
TCHAR buffer[MAX_PATH] = { 0 }; GetModuleFileName(NULL, buffer, MAX_PATH);
To get the directory path without the file name, you can use the following function:
#include <windows.h> #include <string> #include <iostream> std::wstring ExePath() { TCHAR buffer[MAX_PATH] = { 0 }; GetModuleFileName(NULL, buffer, MAX_PATH); std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\/"); return std::wstring(buffer).substr(0, pos); } int main() { std::cout << "my directory is " << ExePath() << "\n"; }
The above is the detailed content of How to Retrieve the Current Directory Path in C ?. For more information, please follow other related articles on the PHP Chinese website!