Windows API C++ | Problem with GetOpenFileName / OPENFILENAME

I’m new to C++
I need to return the path to the file that the user has selected. For this i use winapi -> OPENFILENAME. When i try to return file path, i get only 1 character ("C" for disk C).
My code:

LPWSTR fileBuffer = new wchar_t[256];
OPENFILENAME ofn = { 0 };
        ofn.lStructSize = sizeof(OPENFILENAME);
        ofn.hwndOwner = hwnd;
        ofn.lpstrFile = fileBuffer;
        ofn.lpstrFile[0] = '\0';
        ofn.nMaxFile = 256;
        ofn.lpstrFilter = NULL;
        ofn.nFilterIndex = 1;
        ofn.lpstrFileTitle = NULL;
        ofn.nMaxFileTitle = 0;
        ofn.lpstrInitialDir = NULL;
        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

if (GetOpenFileName(&ofn) == TRUE)
{
    printf("File name: %s\n", ofn.lpstrFile);
}

i tried to increase the buffer size, return the value of ofn.lpstrFile. The first does not change anything, the second returns a int value of disk letter

>Solution :

You are using wchar (needed by OPENFILENAME) which is not the same as char (as expected with printf) if you are using wide mode for windows.

Use wprintf or you can use printf using ‘%S’ (captial) to tell printf to print wide characters

Leave a Reply