Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use boost::filesystem with std::ifstream?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.hpp header provides equivalent components, in namespace boost::filesystem, except that the seven const char* arguments have been replaced by const path& arguments.

The Filesystem Library’s fstream.hpp header simply uses the standard library components as base classes, and then redeclares constructors and open functions to take arguments of type const path& instead of const char*.

It’s documented use is in the 2 minute tutorial, and the examples.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading