使用GetOpenFileName只获取路径之外的文件名

Getting only the filename out of the path with GetOpenFileName

本文关键字:文件名 路径 GetOpenFileName 获取 使用      更新时间:2024-05-09

所以我有这个代码:

OPENFILENAME ofn;
char file_name[100];
ZeroMemory(&ofn, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = NULL;
ofn.lpstrFile = file_name;
ofn.lpstrFile[0] = '';
ofn.nMaxFile = 100;
ofn.lpstrFilter = "Dynamic Link Libraries (.dll)*.dll";
ofn.nFilterIndex = 1;
GetOpenFileName(&ofn);
cout << (const char*)ofn.lpstrFile << endl;

它只是定义窗口的属性,然后用GetOpenFileName(&ofn)打开一个文件,但当我打印lpstrFile时,我会得到我选择的文件的完整路径。

现在我的问题是,在c++上,如何使用文本替换函数或内置窗口函数,从ofn.lpstrFile中只获得文件名exfile.dll,而不获得C:/hello/file.dll

提前谢谢。

使用std::filesystem::path类获得:

std::filesystem::path myFile = ofn.lpstrFile;
std::filesystem::path fullname = myFile.filename();
cout << fullname.c_str() << endl;

它也适用于@WhozCraig:指出的方法

#pragma comment(lib, "shlwapi.lib")
#include <Shlwapi.h>
PathStripPath(ofn.lpstrFile);