Retrieving the Current Directory
Getting the current directory is a frequent task in programming. For instance, suppose you want to create a file in the same directory where the executable is running. To do this, you need to obtain the current directory's path.
However, when using the GetCurrentDirectory() function as shown below:
LPTSTR NPath = NULL; DWORD a = GetCurrentDirectory(MAX_PATH, NPath); HANDLE hNewFile = CreateFile(NPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
you may encounter an exception. Instead of GetCurrentDirectory(), you should use GetModuleFileName() to retrieve the executable path.
TCHAR buffer[MAX_PATH] = { 0 }; GetModuleFileName(NULL, buffer, MAX_PATH);
For obtaining the directory path without the file name, you can employ the following C 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 Get the Current Directory in C ?. For more information, please follow other related articles on the PHP Chinese website!