I'm trying to have my function return an OPENFILENAME struct. Problem: It returns it fine and everything except that I cannot print the filetitle :S At the moment, it prints the path of the file perfectly fine but when it comes to printing the file title via cout, it prints a bunch of random characters and I have no clue why. Please help me.

OPENFILENAME OpenFileDialog(bool InvertSlashes = false)
{
    OPENFILENAME OFN;
    char FilePath[MAX_PATH];
    char FileTitle[MAX_PATH];

    ZeroMemory(&OFN, sizeof(OFN));
    OFN.lStructSize = sizeof(OFN);

    OFN.lpstrInitialDir = 0;
    OFN.lpstrFile = FilePath;
    OFN.lpstrFile[0] = '\0';
    OFN.nFilterIndex = 1;
    OFN.nMaxFile = sizeof(FilePath);
    OFN.lpstrFileTitle = FileTitle;
    OFN.lpstrFileTitle[0] = '\0';
    OFN.nMaxFileTitle = sizeof(FileTitle);
    OFN.lpstrFilter = "All Files\0*.*\0\0";
    OFN.lpstrDefExt = 0;
    OFN.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;

    if (GetOpenFileName(&OFN) != 0)
    {
        if (InvertSlashes)
        {
            string TempFilePath = OFN.lpstrFile;
            replace(TempFilePath.begin(), TempFilePath.end(), '\\', '/');
            strcpy(OFN.lpstrFile, TempFilePath.c_str());
        }
    }
    return OFN;
}




int main()
{
    OPENFILENAME Test = OpenFileDialog();
    cout<<Test.lpstrFile<<endl;        //Prints perfectly fine.
    cout<<Test.lpstrFileTitle<<endl;   //Prints random characters.
}

The reason for the problem is because both FileTitle and FilePath are allocated on the stack, which disappears just as soon as the function returns. The solution is to pass the filename and path to the function as parameters so that they don't get destroyed when openFileDialog() returns.

BOOL OpenFileDialog(char*path, char* filename, bool InvertSlashes = false)



int main()
{
   char path[_MAX_PATH];
   char filename[_MAX_PATH];
   OPENFILENAME of = OpenFileDialog(path, filename);

 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.