user2688153
user2688153

Reputation: 47

Getting a file folder from Open File Dialog

I'm a newbie to c++, and I can't figure out how simple get a directory of chose file from open file dialog. I'm trying to use standard functions, in my case it's GetFullPathName. That's how I'm trying to do:

OPENFILENAME ofn;       // common dialog box structure
char szFile[260];       // buffer for file name
HANDLE hf;              // file handle
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not 
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
//ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

// Display the Open dialog box. 

if (GetOpenFileName(&ofn) == TRUE)
    hf = CreateFile(ofn.lpstrFile,
    GENERIC_READ,
    0,
    (LPSECURITY_ATTRIBUTES) NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    (HANDLE) NULL);


char buffer[MAX_PATH];
char *buffer2[MAX_PATH];
GetFullPathName(ofn.lpstrFile,
    ofn.nMaxFile,
    buffer,
    buffer2);

//PathRemoveFileSpec(ofn.lpstrFile);
MessageBox(hWnd, buffer, "Tutorial", 0); // and show the path

Upvotes: 1

Views: 3527

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37192

When GetOpenFileName() returns, the chosen file is stored in the buffer you provided via the lpstrFile member. This is the full path to the file (e.g. C:\Path\To\File.txt).

To get the folder the file is in all you need to do is strip off the last component. You can do this manually by searching the string backwards for the last backslash character, or use one of the utility functions to do it for you:

char chFolderPath[MAX_PATH];
StringCchCopy(chFolderPath, MAX_PATH, ofn.lpstrFile);
PathRemoveFileSpec(chFolderPath);
// chFolderPath now contains "C:\Path\To"

Note you'll need to #include <shlwapi.h> and link with shlwapi.lib to use the PathRemoveFileSpec function.

Upvotes: 1

Related Questions