【问题标题】:Is there a OS library for C++是否有 C++ 的操作系统库
【发布时间】:2021-03-28 02:30:48
【问题描述】:

假设我想做一个文件管理器,我需要获取给定路径中所有文件的名称。在 python 中,我会这样做:os.listdir(path)。像 OS 模块这样的 c++ 库也是如此。

【问题讨论】:

标签: python c++ operating-system filesystems c++17


【解决方案1】:

你可以使用

#include <filesystem>

为此。

对于一些较旧的编译器,您可能需要检查是否只有实验文件系统可用并使用它。

#pragma once

#if __has_include(<filesystem>)

#include <filesystem>
namespace filesystem = std::filesystem;

#else

#include <experimental/filesystem>
namespace filesystem = std::experimental::filesystem;

#endif

然后遍历文件:

   for (auto it : filesystem::directory_iterator("path/to/iterate"))
   {
       // Use it.path
   }

   // Or recursively
   for (auto it : filesystem::recursive_directory_iterator("path/to/iterate"))
   {
       // Use it.path
   }

【讨论】:

  • 请注意,#pragma once__has_include 都不是标准 C++。
  • __has_include 自 c++17 en.cppreference.com/w/cpp/preprocessor/include 以来是标准的,而#pragma once 不是标准的,由大多数编译器实现
  • 感谢__has_include 的更正。而且,是的,#pragma once 由许多编译器实现,但在某些情况下它不能被依赖(例如,同一文件具有多个路径的网络),这就是它不标准的原因。
【解决方案2】:

你可以像这样导入boost's filesystem libs

#include <boost/filesystem.hpp>

也许这行得通?

【讨论】:

  • 虽然 Boost 是一种宝贵的资源,但也有标准答案,在本例中为
猜你喜欢
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 2018-02-07
  • 1970-01-01
  • 2021-12-31
  • 2012-08-16
相关资源
最近更新 更多