I’m using libcurl (HTTP transfer library) with C++ and trying to download files from remote HTTP servers. As file is downloaded, my callback function is called multiple times (e.g. every 10 kb) to send me buffer data.
Basically I need something like “string bufer”, a data structure to append char buffer to existing string. In C, I allocate (malloc) a char* and then as new buffers come, I realloc and then memcpy so that I can easily copy my buffer to resized array.
In C, there are multiple solutions to achieve this.
- I can keep using
malloc,realloc,memcpybut I’m pretty sure that they are not recommended in C++. - I can use
vector<char>. - I can use
stringstream.
My use cases is, I’ll append a few thousands of items (chars) at a time, and after it all finishes (download is completed), I will read all of it at once. But I may need options like seek in the future (easy to achieve in array solution (1)) but it is low priority now.
What should I use?
I’d go for
stringstream. Just insert into it as you recieve the data, and when you’re done you can extract a fullstd::stringfrom it. I don’t see why you’d want toseekinto an array? Anyway, if you know the block size, you can calculate where in the string the corresponding block went.