0

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?

user17732522
  • 53,019
  • 2
  • 56
  • 105
Happy Machine
  • 987
  • 8
  • 30
  • 1
    You cannot print `dir_entry` into `std::cout`, you probably meant `dir_entry.path()` or `dir_entry.path().string()`. –  Jun 20 '22 at 12:02
  • This is from the official docs – Happy Machine Jun 20 '22 at 12:03
  • 1
    Indeed. Looks like your implementation doesn't implement `operator<<` for `directory_entry`. –  Jun 20 '22 at 12:04
  • 1
    Which version of Clang are you using? Are you using libc++ or libstdc++? – user17732522 Jun 20 '22 at 12:05
  • Are you on windows or linux? possible dupe: https://stackoverflow.com/questions/57377349/implicit-conversion-between-stdfilesystempath-and-stdstring-should-it-hap – NathanOliver Jun 20 '22 at 12:06
  • 4
    There was [LWG issue 3171](https://cplusplus.github.io/LWG/issue3171). 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](https://cplusplus.github.io/LWG/issue2989). – user17732522 Jun 20 '22 at 12:08
  • 2
    @HappyMachine -- minor point: cppreference is a very good site, but it is not in any sense "official". – Pete Becker Jun 20 '22 at 12:16

1 Answers1

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

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52