0

I'm having an issue with my code.

What I'm trying to do is get the executable path dynamically, then assign it to char* n_argv array. I've really been trying for some time, but decided to ask here. Sorry if this is an inapproptiate question.

int main (int argc, char** argv){

    char szPathToExe[MAX_PATH];
    GetModuleFileNameA(NULL, szPathToExe, MAX_PATH);

    std::string path(szPathToExe);
    path.append("other_argument");
    char *n_argv = path.c_str();

   argv = n_argv;


}

Any idea on how to approach this? Thank you in advance!

Jezis Marja
  • 11
  • 1
  • 3
  • Just use `wchar_t const *` for `n_argv` array (note that `"other_argument"` can not be assigned to `char *`). – user7860670 Jan 15 '18 at 18:50
  • Use `GetModuleFileNameA` to get a char version. –  Jan 15 '18 at 18:52
  • As @manni66 says use `GetModuleFileNameA` but also consider that this will convert any Unicode characters in the pathname to code-page based characters. Is this what you want to do? Perhaps you should be using Unicode throughout as you have selected this in your project options. – Richard Critten Jan 15 '18 at 19:03
  • in windows code you should generally stick with wchar_t rather than converting to char. If you need char then use the functions in gkpln3 answer – pm100 Jan 15 '18 at 20:05
  • To add some context, a lot of calls in the Windows API are actually macros (#define). For example `GetModuleFileName` is a macro, and depending on your project settings (if `UNICODE` is defined), the `#define GetModuleFileName` will be either `GetModuleFileNameW` (using `wchar`) or `GetModuleFileNameA` (using `char`). Note that Windows internally uses unicode, so `GetModuleFileNameA` will be slightly slower than `GetModuleFileNameW` since it has to convert the `char`s to `wchar`s before reaching the actual Windows code. – Kevin Doyon Jan 15 '18 at 20:09
  • 1
    `n_argv` is not an array. It is a pointer. – Lightness Races in Orbit Jun 24 '19 at 12:10

2 Answers2

0

Use wcstombs or wcstombs_s

https://msdn.microsoft.com/en-us/library/5d7tc9zw.aspx

size_t wcstombs(  
   char *mbstr,  
   const wchar_t *wcstr,  
   size_t count   
);  
size_t _wcstombs_l(  
   char *mbstr,  
   const wchar_t *wcstr,  
   size_t count,  
   _locale_t locale  
);
gkpln3
  • 1,317
  • 10
  • 24
-1

Here's a simple implementation based on this post you can use:

#include <windows.h>    

auto wide_to_char(const WCHAR* source) {
    const auto wide_char_file_path_length = wcslen(source);
    auto destination_buffer = std::make_unique<char[]>(wide_char_file_path_length + 1);

    auto array_index = 0;
    while (source[array_index] != '\0') {
        destination_buffer.get()[array_index]= static_cast<CHAR>(source[array_index]);
        array_index++;
    }

    destination_buffer.get()[array_index] = '\0';
    return destination_buffer;
}
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185