首页 > 解决方案 > C++ CodeBlocks 升级到 C++17 不能使用 std::filesystem

问题描述

我需要能够列出目录中的文件,因此我正在尝试将 CodeBlocks 中的 C++ 版本升级到 C++ 17,以便我可以使用文件系统。为此,我按照http://candcplusplus.com/enable-c17-in-code-blocks-mingw-gcc-for-all-version-with-pictures#:~:text=Enabling%20the%中概述的步骤进行操作20C%2B%2B17,创建%20a%20项目

我不需要做太多改动,CodeBlocks 20.03 和 MinGW 8.1.0 已经安装好了。从我构建 wxWidgets 开始,MinGW 就已经在我的路径中了。Settings->Compiler...->Toolchain executables 选项卡我不必进行任何更改,并在 CodeBlocks 中显示为:

在此处输入图像描述

我还选中了在编译器设置中使用 C++ 17 的复选框,如下所示

在此处输入图像描述

我按照说明在网站上运行了测试程序,得到了“真!”。

但是,当我将基本测试程序更改为此,尝试使用文件系统读取目录中的文件时,出现错误:

#include <iostream>
#include <filesystem>

using namespace std;

int main()
{
    const int i=90;

    if constexpr (i) //'if constexpr' is part of C++17
    {
        cout << "True!";
    }
    else
    {
        cout<<"False" ;
    }

    std::string path = "../MagicProgCPP/files/debug images/";
    for (const auto & entry : filesystem::directory_iterator(path))
    {
        cout << entry.path() << std::endl;
    }


    cin.get();
    return 0;
}

程序停止构建,打开文件 fs_path.h 并在此行停止:

#ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
      if (__p.is_absolute()
      || (__p.has_root_name() && __p.root_name() != root_name()))     <----- ******STOPS HERE
    operator=(__p);
      else
    {
      string_type __pathname;
      if (__p.has_root_directory())
        __pathname = root_name().native();
      else if (has_filename() || (!has_root_directory() && is_absolute()))
        __pathname = _M_pathname + preferred_separator;
      __pathname += __p.relative_path().native(); // XXX is this right?
      _M_pathname.swap(__pathname);
      _M_split_cmpts();
    }
#else
      // Much simpler, as any path with root-name or root-dir is absolute.
      if (__p.is_absolute())
    operator=(__p);
      else
    {
      if (has_filename() || (_M_type == _Type::_Root_name))
        _M_pathname += preferred_separator;
      _M_pathname += __p.native();
      _M_split_cmpts();
    }
#endif
      return *this;
    }

我在构建日志中收到此错误:

C:\Program Files\CodeBlocks\MinGW\lib\gcc\x86_64-w64-mingw32\8.1.0\include\c++\bits\fs_path.h|237|error: no match for 'operator!='(操作数类型为'std::filesystem::__cxx11::path' 和 'std::filesystem::__cxx11::path')|

当我输入路径并且其中有文件时,我非常有信心路径存在。构建日志消息表明我可能没有使用 C++17?但是当我单击构建时,这是程序用于构建的行:

g++.exe -Wall -fexceptions -g -Wall -std=c++17  -c E:\testc17\main.cpp -o obj\Debug\main.o

我究竟做错了什么?谢谢

标签: c++codeblocks

解决方案


自 2018 年 7 月以来,已修复错误 78870。
您应该将以下库添加到项目选项 -> 链接器设置 -> 链接库:stdc++fs. 我尝试使用 MinGW gcc 8.1.0(通过 CodeBlocks)编译您的代码,并且一切正常(显然使用另一条路径,因为我没有与您相同的目录)。 在此处输入图像描述 您还可以像这样添加对搜索目录是否存在的检查:

namespace fs = std::filesystem;
std::string mypath { "../MyDir" };
if(fs::exists(mypath))
{
    for(const auto & entry : fs::directory_iterator(path))
    {
        cout << entry.path() << std::endl;
    }
}

推荐阅读