I’m using Ubuntu 20.04 LTS with C++ 20 and boost 1.71.0.
The following compiles without error and outputs the sample file content:
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <filesystem>
int main() {
boost::filesystem::path output_dir = boost::filesystem::path("/out/");
boost::filesystem::path sample_file = output_dir / "sample.txt";
std::ifstream ifs{sample_file};
std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
std::cout << "Sample file content: " << std::endl << content << std::endl;
return 0;
}
So how does this work? Is this boost::filesystem::path
implicitly cast to std::string
?
Is this safe to use?
2
Answers
The documentation for Boost Filesystem fstream indicates:
It’s documented use is in the 2 minute tutorial, and the examples.
std::basic_fstream
has a constructor which takes a templatedFSPath
type https://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstreamThis overload should only accept
std::filesystem::path
but it looks like libstdc++ accepts any class which conforms tostd::filesystem::path
‘s interface. This is non-standard and doesn’t compile with other standard libraries: https://godbolt.org/z/njr5s3harYou can fix this with the
boost/filesystem/fstream.hpp
header, but you’ll have to changestd::ifstream
toboost::filesystem::fstream
. A better fix is to just change to usingstd::filesystem
which is mostly a drop in replacement forboost::filesystem
.