I'm having trouble converting from LPSTR to const char* in MinGW under Windows.
#include <dirent.h>
#include <cstdio>
#include <fstream>
#include <windows.h>
int main() {
DIR *dir;
struct dirent *ent;
LPSTR buffer;
GetCurrentDirectory(100, buffer);
const char *str = *buffer;
dir = opendir(*str);
return 0;
}
What I'm trying to do is grab a list of all the current files in a directory and write it to a file; I can do the latter, but the former is giving me some trouble. I can figure out how to read the directory once I can convert the different variable types.
I know what LPSTR is, but I don't know how to apply it to this code.
Do not suggest using atlbase.h
because MinGW does not support it, and I'm not willing to go back to Visual unless absolutely necessary.
You seem to be a bit confused about indirection.
LPSTR
is achar*
. It is a pointer to achar
(or, as is the case here, a pointer to the initial element of an array ofchar
).When you call
GetCurrentDirectory
, you need to pass it a pointer to the initial element of an array ofchar
and the size of that array. So, what you need to do is declare an array and pass that into the function. For example,With your current implementation, your program will assuredly crash because
buffer
is uninitialized, soGetCurrentDirectory
will attempt to write to some random location in memory.You should also check the return value of
GetCurrentDirectory
to ensure that it completed successfully and that the buffer contains the complete path. Its documentation explains the values that it may return.Once you have the path, you can pass it directly to
opendir
: the arraybuffer
is implicitly convertible to a pointer to its initial element--that is, thechar[MAX_PATH]
can be converted to achar*
--and thatchar*
can be implicitly converted to thechar const*
required byopendir
:Do note that the signature of
GetCurrentDirectory
depends on whether theUNICODE
macro is defined or not: if you are compiling your program for Unicode, it actually takes a pointer to an array ofwchar_t
. If you build a Unicode program, you will need to account for this (you should use Unicode if you can).