How to get Current Directory?


Question

I've been doing this in C# and Delphi ,but C++ is evil.The purpose is to create a file in the current directory(where the executable is running).

My code:

LPTSTR NPath = NULL;
DWORD a = GetCurrentDirectory(MAX_PATH,NPath);
HANDLE hNewFile = CreateFile(NPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

I get exception at GetCurrentDirectory().

Please tell me why I get an exception and how do I make it easier in C++?

1
53
5/17/2009 7:17:31 PM

Accepted Answer

I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.

To get the executable path use GetModuleFileName:

char buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH );

Here's a C++ function that gets the directory without the file name:

#include <windows.h>
#include <string>
#include <iostream>
using namespace std;;

string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileName( NULL, buffer, MAX_PATH );
    string::size_type pos = string( buffer ).find_last_of( "\\/" );
    return string( buffer ).substr( 0, pos);
}

int main() {
    cout << "my directory is " << ExePath() << "\n";
}
111
11/3/2016 10:27:13 AM

GetCurrentDirectory does not allocate space for the result, it's up to you to do that.

TCHAR NPath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, NPath);

Also, take a look at Boost.Filesystem library if you want to do this the C++ way.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon