打开本地弹窗,获取文件名
#include<windows.h>
#include<iostream>
#include<string.h>
using namespace std;
//将一个LPCWSTR转换为string
string Lpcwstr2String(LPCWSTR lps) {
int len = WideCharToMultiByte(CP_ACP, 0, lps, -1, NULL, 0, NULL, NULL);
if (len <= 0) {
return "";
}
else {
char* dest = new char[len];
WideCharToMultiByte(CP_ACP, 0, lps, -1, dest, len, NULL, NULL);
dest[len - 1] = 0;
string str(dest);
delete[] dest;
return str;
}
}
//新建一个对话窗口,选择文件
string get_path() {
OPENFILENAME ofn;
char szFile[300];
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = (LPWSTR)szFile;
ofn.lpstrFile[0] = '\0';
LPTSTR lpstrCustomFilter;
DWORD nMaxCustFilter;
ofn.nFilterIndex = 1;
LPTSTR lpstrFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"ALL\0*.*\0Text\0*.TXT\0";
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
string path_image = "";
if (GetOpenFileName(&ofn)) {
path_image = Lpcwstr2String(ofn.lpstrFile);
return path_image;
}
else
{
return "";
}
}
int main() {
string path_weight = "";
path_weight = get_path();
cout << "-------" << path_weight << endl;
system("pause");
return 0;
}
可能出现的bug:
1、选择完文件后,当前的目录变成了被选择文件的路径,如果之后的代码存在用类似“../”相对路径的方式,可能出错。
2、#include<windows.h>由于导入的这个库会导致一些类似于:“::、)”报错,这时候需要在类似于:std::min()……处加上括号:(std::min)();



浙公网安备 33010602011771号