Ran into a similar question on SO , here is a brief overview of the options:
If std::filebuf
, then this is the fastest option suggested by Kitty :
std::ifstream file(filename); std::streambuf* content = file.rdbuf();
If you want std::string
, then something like this:
std::ifstream file(filename); std::string content( (std::istreambuf_iterator<char>(file) ), (std::istreambuf_iterator<char>() ) );
Similarly, you can shove in std::vector<char>
.
Well, if you need char*
, then:
FILE* f = fopen(filename, "r"); // Получаем размер файла fseek(f, 0, SEEK_END); size_t size = ftell(f); // Выделяем память, читаем данные char* content = new char[size]; // Или (char *)malloc(size), тогда будет чистый C. rewind(f); fread(where, sizeof(char), size, f);
BUT: this is all for files in the local file system. For HTTP, you can do Boost.Asio with something in the spirit of
ip::tcp::iostream stream; stream.expires_from_now(boost::posix_time::seconds(60)); stream.connect("www.boost.org", "http"); stream << "GET /LICENSE_1_0.txt HTTP/1.0\r\n"; stream << "Host: www.boost.org\r\n"; stream << "Accept: */*\r\n"; stream << "Connection: close\r\n\r\n"; stream.flush(); std::streambuf* content = stream.rdbuf();
Or use, for example, Urdl :
urdl::istream stream("http://www.boost.org/LICENSE_1_0.txt"); std::streambuf* content = stream.rdbuf();
Or use libcurl (there are examples by reference).