C++ 打开文件夹
作者:野牛程序员:2024-01-22 17:44:07 C++阅读 2969
在C++中,要打开文件夹(目录),可以使用 <filesystem>
头文件中的 std::filesystem::directory_iterator
。以下是一个简单的示例代码,演示如何打开文件夹并列举其中的文件:
#include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::string folderPath = "/path/to/your/folder"; // 替换为实际文件夹路径 try { // 使用directory_iterator遍历文件夹 for (const auto& entry : fs::directory_iterator(folderPath)) { std::cout << entry.path() << std::endl; } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }
请确保将 "/path/to/your/folder"
替换为实际的文件夹路径。这个程序将遍历指定文件夹中的所有文件和子文件夹,并输出它们的路径。
注意:使用 <filesystem>
需要 C++17 或更高的标准支持。如果编译器不支持 C++17,请检查并更新编译器的设置。
如果编译器不支持 <filesystem>
,可以考虑使用第三方库,比如Boost.Filesystem。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
