Skip to content

Instantly share code, notes, and snippets.

@kbinani
Created December 1, 2014 02:58
Show Gist options
  • Save kbinani/01d4d609c5bb82324862 to your computer and use it in GitHub Desktop.
Save kbinani/01d4d609c5bb82324862 to your computer and use it in GitHub Desktop.
PHP's file_get_contents function in C++
#include <fstream>
inline std::string file_get_contents(std::string const& path)
{
return (std::stringstream() << std::ifstream(path).rdbuf()).str();
}
@divinity76
Copy link

divinity76 commented Feb 28, 2019

this wouldn't compile for me, giving me

prog.cc: In function 'std::string file_get_contents(const string&)':
prog.cc:5:28: error: invalid use of incomplete type 'std::stringstream' {aka 'class std::__cxx11::basic_stringstream<char>'}
    5 |  return (std::stringstream() << std::ifstream(path).rdbuf()).str();
      |                            ^
In file included from /opt/wandbox/gcc-head/include/c++/9.0.1/ios:38,
                 from /opt/wandbox/gcc-head/include/c++/9.0.1/istream:38,
                 from /opt/wandbox/gcc-head/include/c++/9.0.1/fstream:38,
                 from prog.cc:1:
/opt/wandbox/gcc-head/include/c++/9.0.1/iosfwd:108:11: note: declaration of 'std::stringstream' {aka 'class std::__cxx11::basic_stringstream<char>'}
  108 |     class basic_stringstream;
      |           ^~~~~~~~~~~~~~~~~~

and adding #include <sstream> gave me:

 prog.cc: In function 'std::string file_get_contents(const string&)':
 prog.cc:6:62: error: 'class std::basic_ostream<char>' has no member named 'str'
     6 |  return (std::stringstream() << std::ifstream(path).rdbuf()).str();
       |                                                              ^~~

but changing it to

#include <fstream>
#include <sstream>

std::string file_get_contents(std::string const& path)
{
    std::stringstream ss;
    ss << std::ifstream(path).rdbuf();
    return ss.str();
}

compiled just fine :)

ps, i think std::ostringstream is a better fit, and that also compiles for me. (iirc ostringstream is slightly less versatile but faster than stringstream) soo

#include <fstream>
#include <sstream>

std::string file_get_contents(std::string const& path)
{
    std::ostringstream ss;
    ss << std::ifstream(path).rdbuf();
    return ss.str();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment