Determining Current Directory
In C , obtaining the current directory where an executable is running can be crucial for tasks like creating files or managing resources. However, using GetCurrentDirectory() may lead to exceptions as demonstrated in the example provided.
Addressing the Exception
The issue arises because GetCurrentDirectory() expects a valid buffer to store the current directory path. In the provided code, NPath is initially set to NULL. Assigning a NULL pointer to the GetCurrentDirectory() function causes an exception.
Alternative Approaches
Instead of using GetCurrentDirectory(), several other methods can be employed to obtain the current directory:
1. GetModuleFileName:
To retrieve the executable path, which includes both the directory and filename, use GetModuleFileName():
TCHAR buffer[MAX_PATH] = { 0 }; GetModuleFileName(NULL, buffer, MAX_PATH);
2. Extracting Directory Path from Executable Path:
Once the executable path is obtained, you can extract the directory path by finding the last occurrence of "" or "/" in the path:
std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\/"); std::wstring directoryPath = std::wstring(buffer).substr(0, pos);
This provides the directory path without the filename.
Example Function:
Here's an example function that returns the directory path of the executable:
#include <windows.h> #include <string> 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); }
Usage:
std::cout << "Current directory: " << ExePath() << std::endl;
By utilizing these alternative approaches, you can effectively obtain the current directory and avoid exceptions related to GetCurrentDirectory().
The above is the detailed content of How to Avoid Exceptions When Getting the Current Directory in C ?. For more information, please follow other related articles on the PHP Chinese website!