Вопрос

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 a char*. It is a pointer to a char (or, as is the case here, a pointer to the initial element of an array of char).

When you call GetCurrentDirectory, you need to pass it a pointer to the initial element of an array of char and the size of that array. So, what you need to do is declare an array and pass that into the function. For example,

char buffer[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buffer);

With your current implementation, your program will assuredly crash because buffer is uninitialized, so GetCurrentDirectory 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 array buffer is implicitly convertible to a pointer to its initial element--that is, the char[MAX_PATH] can be converted to a char*--and that char* can be implicitly converted to the char const* required by opendir:

DIR* dir = opendir(buffer);

Do note that the signature of GetCurrentDirectory depends on whether the UNICODE macro is defined or not: if you are compiling your program for Unicode, it actually takes a pointer to an array of wchar_t. If you build a Unicode program, you will need to account for this (you should use Unicode if you can).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top