Search code examples
c++crashconsole-applicationaccess-violationopenfiledialog

Wierd access violation error message when trying to use an openFile dialog window


I am still kinda bad in c++ so pls dont mind my bad code or my missing knowledge. The project is about chosing a file and the paste it in the console for the user to read and i thought the best way would be using a dialog window (and i get more practice using the winapi).

Here my code for the window:

OPENFILENAMEA NameOfFile;
ZeroMemory(&NameOfFile, sizeof(NameOfFile));
NameOfFile.nFileOffset = 1;
char szFile[260];
NameOfFile.lpstrFile[0] = '\0';
NameOfFile.lpstrFile = szFile;
NameOfFile.nMaxFile = 4096;
NameOfFile.Flags = OFN_ALLOWMULTISELECT;
if (GetOpenFileName(&NameOfFile)) {
    
    cout << "opened";
}

Now the wierd thing. The Programm crashes with the error "-1073741819". Google said its an access violation of smth (no clue what exactly it means).

When i comment out the ZeroMemory function i got a linker and compiler error that NameOfFile is apparently not initialized??? (but if its not commented it compiles normally?!)


Solution

  • here the code i use from now on. I fixed the problem with LPWSTR trough making szFile a TCHAR and converting it into LPWSTR in FILE. Not the best but enoght for me right now.

    LPWSTR FILE{};
    OPENFILENAME NameOfFile;
    ZeroMemory(&NameOfFile, sizeof(NameOfFile));
    NameOfFile.lStructSize = sizeof(NameOfFile);
    TCHAR szFile[MAX_PATH];
    NameOfFile.lpstrFile = szFile;
    NameOfFile.nMaxFile = sizeof(szFile);
    NameOfFile.Flags = OFN_ALLOWMULTISELECT;
    if (GetOpenFileName(&NameOfFile))
    {
        FILE = (LPWSTR)szFile;
    }
    

    For everyone that wants to paste this, don´t forget the file filters. Otherwise you wont be able to see any files if the windows opens for you. More of that in the documentation