c++openfiledialoglpstr

How to save ofn.lpstrFile to string properly?


Hi i am trying to make a GUI for image compare software. The idea is to choose a picture with OPENFILENAME, then get its address with ofn.lpstrFile then make a histogram for that image. So i use:

return(ofn.lpstrFile);

I can cout the address or write it to an .xml file and the address is correct, but when i am trying to do the histogram it gives me all zeros. Behaves like the address was invalid.

Any ideas ?

my code :

    string path=browse(); //getting the string from ofn.lpstrFile

    path.c_str();
    replace(path.begin(), path.end(), '\\', '/'); //converting backslash to slash also may be the problem       
    HistCreation(path,root_dir); 

and

void HistCreation(string path,string root_dir) {

Mat img;
img = imread(path); // here if i manually enter the address everything works fine, if I insert the path then loads empty image

.
.
.

I also tried

char * cstr = new char[path.length() + 1];
    std::strcpy(cstr, path.c_str());

Did not work either


Solution

  • std::string returns the string and that's all you need. This is example to open a bitmap file.

    (Edit)

    #include <iostream>
    #include <string>
    #include <windows.h>
    
    std::string browse(HWND hwnd)
    {
        std::string path(MAX_PATH, '\0');
        OPENFILENAME ofn = { sizeof(OPENFILENAME) };
        ofn.hwndOwner = hwnd;
        ofn.lpstrFilter = 
            "Image files (*.jpg;*.png;*.bmp)\0*.jpg;*.png;*.bmp\0"
            "All files\0*.*\0";
        ofn.lpstrFile = &path[0];
        ofn.nMaxFile = MAX_PATH;
        ofn.Flags = OFN_FILEMUSTEXIST;
        if (GetOpenFileName(&ofn))
        {
            //string::size() is still MAX_PATH
            //strlen is the actual string size (not including the null-terminator)
            //update size:
            path.resize(strlen(path.c_str()));
        }
        return path;
    }
    
    int main()
    {
        std::string path = browse(0);
        int len = strlen(path.c_str());
        if (len)
            std::cout << path.c_str() << "\n";
        return 0;
    }
    

    Note, Windows uses NUL-terminated C-strings. It knows the length of the string by looking for the zero at the end.

    std::string::size() is not always the same thing. We can call resize to make sure they are the same thing.


    You shouldn't need to replace \\ with /. If your library complains about \\ then replace as follows:

    Example:

    ...
    #include <algorithm>
    ...
    std::replace(path.begin(), path.end(), '\\', '/');
    

    Use std::cout to examine the output instead of guessing if it worked or not. In Windows program you can use OutputDebugString or MessageBox to see what the string is.

    HistCreation(path, root_dir);
    

    I don't know what root_dir is supposed to be. If HistCreation fails or it has the wrong parameter then you have a different problem.