-1

The following function works fine when returning the Windows documents path if it contains all English characters; but returns gibberish if the path contains non English characters, such as Japanese. Any solutions to this problem?

DLLEXPORT char* GetDocPath()
{
    wchar_t Folder[1024];
    HRESULT hr = SHGetFolderPathW(0, CSIDL_MYDOCUMENTS, 0, 0, Folder);

    if (SUCCEEDED(hr))
    {
        char str[1024];
        wcstombs(str, Folder, 1023);
        return str;
    }
    else return NULL;
}
Mirks
  • 1
  • 2
    Thou shalt not return a local array. They [decay to pointers](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) and you're stuck with a pointer to invalid storage. – user4581301 May 25 '20 at 23:30
  • 1
    Firstly, `str` is local, and returning it will cause Undefined Behaviour in the caller. Secondly, what is the gibberish and how do you show it? Oh, and thirdly, what is your locale? – Useless May 25 '20 at 23:30
  • 1
    Sorry, last one - fourthly: you should check the return value of `wcstombs` - did it succeed? – Useless May 25 '20 at 23:31
  • Additionally, `wctombs` uses the system default charset (locale). Are you sure your system codepage contains Japanese? Consider `WideCharToMultiByte` instead, it contains the codepage as a parameter. And yes, memory allocation. – Seva Alekseyev May 25 '20 at 23:50
  • 1
    Conversion from Unicode to mbcs is lossy. Keep it as Unicode to avoid round trip issues. – Raymond Chen May 25 '20 at 23:50

1 Answers1

0

I have had problems in the past when using wchar_t to read french characters, and that is the type you are using in the Folder variable, I solved my problems using the plain char to read those characters, have you already tried that?

If you are on Windows maybe char16_t will do the trick.

Matias Agelvis
  • 951
  • 2
  • 11
  • 22