一.在Windows上,网上流传的几种方法可以打开目录并定位到指定文件:
1.使用系统调用:
使用system()函数执行操作系统的命令行命令。
在命令行命令中,使用explorer /select, 文件路径来打开目录并选中指定文件。例如:
#include
int main() {
std::string filePath = "C:\\路径\\到\\目标\\文件.txt";
std::string command = "explorer /select," + filePath;
system(command.c_str());
return 0;
}
2.使用ShellExecute函数:
使用Windows API的ShellExecute()函数来打开目录并选中指定文件。
使用ShellExecute(NULL, "open", "explorer.exe", "/select, 文件路径", NULL, SW_SHOW);来打开资源管理器并选中指定文件。例如:
#include
int main() {
const char* filePath = "C:\\路径\\到\\目标\\文件.txt";
ShellExecute(NULL, "open", "explorer.exe", ("/select," + std::string(filePath)).c_str(), NULL, SW_SHOW);
return 0;
}
上面两种方式都可以打开并且定位,但是会存在一些问题,使用系统调用会出现一闪而过的黑窗口,还需要实现后台cmd执行,隐藏窗口;ShellExecute这个函数倒是很好用,但是你懂的这是个做什么的函数,基本各大杀毒都会重点监测的东西,带着ShellCode的函数在静态编译下能运行起来都已经是奇迹....
在这种情况下,还有别的骚操作可以实现打开目录,定位指定文件。
二.调用Windows中shlobj_core.h的API函数
1.使用SHOpenFolderAndSelectItems函数:
使用PathFileExistsW() 先判断文件存在不存在
使用ILCreateFromPathW() 获取指定文件路径关联的 ITEMIDLIST 结构
使用SHOpenFolderAndSelectItems() 打开一个 Windows 资源管理器窗口,其中选定了特定文件夹中的指定项目。
遵循SHOpenFolderAndSelectItems()使用规范,Com接口的初始化以及释放
#include
#include
#include
#include
#pragma comment(lib, "Shlwapi.lib")
///
/// 成功则打开文件所在目录并选中文件
///
/// 需提供文件的绝对路径
/// 重命名编辑模式
///
bool open_file_location(const WCHAR* unicode_filename, bool is_edit = false)
{
if (!PathFileExistsW(unicode_filename))
{
return false;
}
PIDLIST_ABSOLUTE pidl = ILCreateFromPathW(unicode_filename);
if (pidl == NULL)
{
return false;
}
CoInitialize(NULL);
HRESULT hr = SHOpenFolderAndSelectItems(pidl, 0, 0, is_edit == true ? OFASI_EDIT : 0);
CoUninitialize();
ILFree(pidl);
return hr == S_OK;
}
int main()
{
open_file_location(L"C:\\Users\\FengTeng\\Desktop\\1.txt");
return 0;
}