1

I cant compile this official cpp filesystem reference example using c++ 17 clang:

https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator

#include <fstream> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/a/b"); std::ofstream("sandbox/file1.txt"); fs::create_symlink("a", "sandbox/syma"); // Iterate over the `std::filesystem::directory_entry` elements explicitly for (const fs::directory_entry& dir_entry : fs::recursive_directory_iterator("sandbox")) { std::cout << dir_entry << '\n'; } std::cout << "-----------------------------\n"; // Iterate over the `std::filesystem::directory_entry` elements using `auto` for (auto const& dir_entry : fs::recursive_directory_iterator("sandbox")) { std::cout << dir_entry << '\n'; } fs::remove_all("sandbox"); } 

The compiler is returning:

/main.cpp:17:19: error: invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream') and 'const fs::directory_entry') std::cout << dir_entry << std::endl;

Can anyone help?

7
  • 1
    You cannot print dir_entry into std::cout, you probably meant dir_entry.path() or dir_entry.path().string(). Commented Jun 20, 2022 at 12:02
  • 1
    Indeed. Looks like your implementation doesn't implement operator<< for directory_entry. Commented Jun 20, 2022 at 12:04
  • 1
    Which version of Clang are you using? Are you using libc++ or libstdc++? Commented Jun 20, 2022 at 12:05
  • 4
    There was LWG issue 3171. The error makes sense if you are using a standard library version that doesn't implement the resolution yet but does implement the resolution to LWG 2989. Commented Jun 20, 2022 at 12:08
  • 2
    @HappyMachine -- minor point: cppreference is a very good site, but it is not in any sense "official". Commented Jun 20, 2022 at 12:16

1 Answer 1

5

There was a defect in C++17 standard that didn't allow operator<< to be called with std::filesystem::directory_entry, reported in LWG 3171. It's now fixed as defect report, but it seems clang only fixed it in version 14: https://godbolt.org/z/3arTcGYvY. gcc seems to have backported the fix to all versions that support std::filesystem (that is, gcc9.1 and up): https://godbolt.org/z/fh7cdMxso

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.