std::ifstream fin("foo.png", std::ios::binary); std::string data; data.reserve(1000000); std::copy(std::istreambuf_iterator<char>(fin), std::istreambuf_iterator<char>(), std::back_inserter(data));
You can read image files with std::string
with this code. Adjust the parameter for the reserve
method to more than 99% of the size of your file. Zero bytes (which you call NULL terminators) are handled correctly with both ifstream
and string
.
I found a good article comparing several binary file loading methods. Here is the fastest way from this article:
std::ifstream fin("foo.png", std::ios::binary); fin.seekg(0, std::ios::end); std::string data; data.resize(fin.tellg()); fin.seekg(0, std::ios::beg); fin.read(&data[0], data.size());
And here is the shortest:
std::ifstream fin("foo.png", std::ios::binary); std::string data((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>());
Update
Something like this can be used to provide a callback function (I have not tested it):
std::ifstream fin("foo.png", std::ios::binary); fin.seekg(0, std::ios::end); ... curl_easy_setopt(m_ctx, CURLOPT_INFILESIZE, fin.tellg()); curl_easy_setopt(m_ctx, CURLOPT_READDATA, (void *)&fin); fin.seekg(0, std::ios::beg); ... static size_t put_callback(void *ptr, size_t size, size_t nmemb, void *data){ std::ifstream* in = static_cast<std::ifstream*>(data); if(in->eof()) return 0; in->read((char *)ptr, size*nmemb); return in->gcount(); }