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?
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