views:

77

answers:

2

I'm using sockets with C++. The program simply requests an HTTP page, reads it into a buffer buf[512], and then displays the buffer. However pages can contain more data than the buffer, so it will cut off if there is no more space left. I can make the buffer size bigger, but that doesn't seem like a good solution. This is the code that I am using:

char buf[512];
int byte_count = recv(sockfd, buf, sizeof(buf), 0);

What would be an alternative to a char array in C++ to use as a buffer?

+1  A: 

There basically isn't one - when using recv, you need to call it repeatedly until it has read all your input. You can of course use more advanced sockets libraries that support growing buffers, but for plain old recv(), a n array of char (or vector of char) is what you need.

You can of course append the data you read into a dynamic buffer such as a string:

string page;
while( len = recv( ... ) ) {
   page.append( buf, len );
}
anon
+2  A: 

Depends on what you intend to do with the data. If you just want to dump it to an output stream, then the proper thing to do is to do what you're doing, but do it in a loop until there's no more data to read, writing the buffer to the output stream after each read.

Mike Baranczak