C++ 打开文本对话框,获取选中文件的路径、名称和后缀名

#include<iostream>
#include<Windows.h>
#include<commdlg.h>
#include<string>
using namespace std;
/******************************************************************************************
Function:        TCHAR2STRING
Description:     TCHAR转string
Input:           str:待转化的TCHAR*类型字符串
Return:          转化后的string类型字符串
*******************************************************************************************/
string TCHAR2STRING(TCHAR* str){
	std::string strstr;
	try
	{
		int iLen = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);

		char* chRtn = new char[iLen * sizeof(char)];

		WideCharToMultiByte(CP_ACP, 0, str, -1, chRtn, iLen, NULL, NULL);

		strstr = chRtn;
	}
	catch (exception e)
	{
	}

	return strstr;
}

int main(){
	while (1){
		OPENFILENAME ofn = { 0 };
		TCHAR strFileName[MAX_PATH] = { 0 };	//用于接收文件名
		ofn.lStructSize = sizeof(OPENFILENAME);	//结构体大小
		ofn.hwndOwner = NULL;					//拥有着窗口句柄
		ofn.lpstrFilter = TEXT("All*.*jpg*.jpgbmp*.bmp");	//设置过滤
		ofn.nFilterIndex = 1;	//过滤器索引
		ofn.lpstrFile = strFileName;	//接收返回的文件名,注意第一个字符需要为NULL
		ofn.nMaxFile = sizeof(strFileName);	//缓冲区长度
		ofn.lpstrInitialDir = NULL;			//初始目录为默认
		ofn.lpstrTitle = TEXT("请选择一个文件"); //窗口标题
		ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY; //文件、目录必须存在,隐藏只读选项
		//打开文件对话框
		if (GetOpenFileName(&ofn)){
			string filePath = TCHAR2STRING(strFileName);
			int start = filePath.find_last_of(\);
			int end = filePath.find_last_of(.);
			string fileName = filePath.substr(start + 1, end - start - 1);
			string exten = filePath.substr(end, filePath.length() - end);
			cout << filePath << endl;
			cout << fileName << endl;
			cout << exten << endl;
		}
		else{
			MessageBox(NULL, TEXT("请选择一文件"), NULL, MB_ICONERROR);
		}
	}
	return 0;
}

示例结果:

经验分享 程序员 微信小程序 职场和发展