[英]Getting a file folder from Open File Dialog
我是C ++的新手,我無法弄清楚從打開文件對話框中獲取所選文件的目錄有多簡單。 我正在嘗試使用標准函數,在我的情況下是GetFullPathName。 那就是我想要做的:
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
當GetOpenFileName()
返回時,所選文件存儲在通過lpstrFile
成員提供的緩沖區中。 這是文件的完整路徑(例如C:\\ Path \\ To \\ File.txt )。
要獲取該文件夾,只需除去最后一個組件即可。 您可以通過向后搜索字符串中的最后一個反斜杠字符來手動執行此操作,或者使用實用程序功能之一為您執行此操作:
char chFolderPath[MAX_PATH];
StringCchCopy(chFolderPath, MAX_PATH, ofn.lpstrFile);
PathRemoveFileSpec(chFolderPath);
// chFolderPath now contains "C:\Path\To"
請注意,您需要#include <shlwapi.h>
並與shlwapi.lib
鏈接才能使用PathRemoveFileSpec
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.