This function should write to szPath the path from which the binary was run. It returns the path for me, but, every 2nd byte in szPath is \0 , as a result, the code below does not work as I wanted. The launch address of the binary: C:\Пользователи\z\source\repos\ProjectName\Debug (many пользователи replace the program with users themselves, I don’t know whether it replaces it or not)

 char szPath[0x100]; GetCurrentDirectory(0x100,(LPWSTR)szPath); 

    2 answers 2

    1) Strangely enough, you set the size of the array, you use decimal numbers in your life, probably? In general, WinAPI defines a special character MAX_PATH which defines the maximum size of a file path. Better to use it.

    2) You specify a buffer for the ASCII string, but use it with the UNICODE version of the function. Will correctly write:

     char szPath[MAX_PATH]; ::GetCurrentDirectoryA(MAX_PATH, szPath); 

    However, this code is not quite suitable if there are national symbols on the way. Therefore, it is better to use the UNICODE string:

     WCHAR szPath[MAX_PATH]; ::GetCurrentDirectoryW(MAX_PATH, szPath); 

    3) And like a cherry on a cake - the GetCurrentDirectory function does not return the path to the executable file. It returns the current directory, and this is something else. It really often coincides with the directory running .exe, but not always. Actually, GetCurrentDirectory is a relic of MS-DOS, in a multitasking system with a graphical interface, the concept of "current directory" makes little sense. It's better to forget about this function at all, it is not needed.

    To get the path to your .exe, you need to use the GetModuleFileName function. For example:

     WCHAR szPath[MAX_PATH]; ::GetModuleFileNameW(NULL, szPath, MAX_PATH); 

    This is a bit simplistic (it would be better to check for an error), but it will work. To get the directory you need to find the first '\' from the end and drop the file name. For example:

     *wcsrchr(szPath, L'\\') = L'\0'; 
    • It works. I did not know about GetModuleFileNameW ( - Daniel Pospelov

    So what did you expect? Why do you have a call to GetCurrentDirectory to explicitly cast szPath to LPWSTR ? Obviously because without it the code was not compiled. That is, your project is created in Unicode mode and GetCurrentDirectory returns the result as a “wide” string of wchar_t characters. It is these "wide" symbols that you observe.

    Why did you even create a project in Unicode mode, if you are not going to work with "wide" lines? Do you need to work with wide lines or not? Further steps depend on the answer to this question.

    • Thank you, I completely forgot about wide characters - Daniel Pospelov