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?
>Solution :
The documentation for Boost Filesystem fstream indicates:
The C++ Standard Library’s header uses
const char*to pass arguments representing file names, with that usage occurring seven times.
The Filesystem Library’s
fstream.hppheader provides equivalent components, in namespaceboost::filesystem, except that the sevenconst char*arguments have been replaced byconst path&arguments.
The Filesystem Library’s
fstream.hppheader simply uses the standard library components as base classes, and then redeclares constructors and open functions to take arguments of typeconst path&instead ofconst char*.
It’s documented use is in the 2 minute tutorial, and the examples.