C++打开文件夹

https://bbs.youkuaiyun.com/topics/392055617?page=1   见2楼

system("start \"\" \"文件夹路径\"");

例:

#include<iostream>

using namespace std;

int main(){
    system("start \"\" \"D:\\test\\hh\\xxx\""); //路径为D:\test\hh\xxx
    return 0;
}

 

转载于:https://www.cnblogs.com/Toya/p/11222453.html

### 使用 C++ 打开文件夹 为了实现在 C++打开文件夹的功能,可以利用 Windows API 函数 `ShellExecute` 或者更现代的方式使用 `std::filesystem` 库来处理路径操作。下面分别介绍这两种方法。 #### 方法一:使用 ShellExecute 打开文件夹 当需要仅打开文件夹而不打开特定文件时,可以通过传递合适的参数给 `ShellExecute` 来实现这一目的。对于只希望展示某个具体文件的位置,则可以在命令行字符串前加上 `/select,` 参数[^2]。 ```cpp #include <windows.h> #include <tchar.h> int main() { // 定义要选择的文件路径 CString filePath = _T("E:\\TestDir\\test.txt"); // 构造 explorer 命令串,注意 /select 后面跟的是逗号分隔符 CString commandLine = _T("/select,"); commandLine += filePath; // 调用 ShellExecute 显示包含选定项目的资源管理器窗口 ShellExecute(NULL, _T("open"), _T("explorer.exe"), commandLine, NULL, SW_SHOWNORMAL); return 0; } ``` 这种方法适用于想要高亮显示某项文件的情况,在实际应用中非常有用,比如在 IM 软件接收到新消息附件后提供快速访问链接。 #### 方法二:使用 std::filesystem (C++17 及以上) 如果只是简单地打开一个文件夹而不需要特别关注其中的内容,那么可以直接调用 `ShellExecute` 并传入文件夹路径作为参数即可;或者采用更加现代化的方法——借助于 C++17 引入的标准库 `<filesystem>` 进行跨平台兼容的操作: ```cpp #include <iostream> #include <string> #include <shellapi.h> // For ShellExecute #include <filesystem> namespace fs = std::filesystem; void OpenFolder(const fs::path& folderPath) { if (!fs::exists(folderPath)) { std::cerr << "The specified path does not exist." << std::endl; return; } SHELLEXECUTEINFO shexi{}; shexi.cbSize = sizeof(SHELLEXECUTEINFO); shexi.fMask = SEE_MASK_INVOKEIDLIST | SEE_MASK_NOCLOSEPROCESS; shexi.lpVerb = L"explore"; shexi.lpFile = folderPath.wstring().c_str(); shexi.nShow = SW_NORMAL; if (!ShellExecuteEx(&shexi)) { DWORD error = GetLastError(); std::wcerr << L"Failed to open the folder with error code: " << error << std::endl; } } int main(){ try{ fs::path targetFolderPath(L"E:\\TestDir"); OpenFolder(targetFolderPath); }catch(const fs::filesystem_error &e){ std::cout<< e.what()<<'\n'; } return 0; } ``` 这段代码展示了如何安全地检查路径是否存在以及错误处理机制,并且通过设置不同的动词 (`lpVerb`) 和标志位 (`fMask`) 实现了探索模式下打开文件夹的行为[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值