简体   繁体   English

从“打开文件”对话框获取文件夹

[英]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. 我是C ++的新手,我无法弄清楚从打开文件对话框中获取所选文件的目录有多简单。 I'm trying to use standard functions, in my case it's GetFullPathName. 我正在尝试使用标准函数,在我的情况下是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

When GetOpenFileName() returns, the chosen file is stored in the buffer you provided via the lpstrFile member. GetOpenFileName()返回时,所选文件存储在通过lpstrFile成员提供的缓冲区中。 This is the full path to the file (eg C:\\Path\\To\\File.txt ). 这是文件的完整路径(例如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. 请注意,您需要#include <shlwapi.h>并与shlwapi.lib链接才能使用PathRemoveFileSpec函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM