【发布时间】:2021-01-14 17:42:34
【问题描述】:
我正在尝试创建一个打开对话框的函数,让用户选择一个文件,然后将其路径作为 std::string 返回。到目前为止我有这个,但我正在尝试获取它,以便它打印并将路径作为字符串返回。
auto GetUserFile() {
OPENFILENAME ofn; // common dialog box structure
char szFile[260]; // buffer for file name
HWND hwnd{}; // owner window
HANDLE hf; // file handle
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = (LPWSTR)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 = L"All\0*.*\0Text\0*.TXT\0"; // I think this sets the file types that can be selected
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);
std::cout << ofn.lpstrFile; // ?? prints a bunch of numbers and letters
// return ofn.lpstrFile; // Want to change this to a string
}
}
我用于this 的 Windows 文档说 lpstrFile 成员“包含路径和文件名”,但我不确定如何将其实际转换为字符串形式,甚至是我自己可以理解的形式。我可能只是使用了错误的转换方法,我尝试将 lpstrfile 转换为 c 字符串和 std::string,但它们也会给出随机数字或引发访问冲突。
【问题讨论】:
标签: c++ path windows-10