rustyengineer
rustyengineer

Reputation: 353

Read() in C/C++ - regarding what is read vs buffer size

I'm trying to read a message (string/text) from the server, and I set the buffer size really large (buffer_size = 1000) so that I only need to read once from the server.

So my question is if the message is exactly 10 bytes, and I call read(socket, buffer, buffer_size), then is it gonna read only 10 bytes, since it is less than the actual buffer size? I guess I'm just curious about the behavior of the call in case what is read is actually not as much as what is expected.

Also if I call the read() again, will it overwrite what is in the buffer? By that I mean empty the buffer and overwrite it with new input.

Upvotes: 0

Views: 4301

Answers (3)

D3Hunter
D3Hunter

Reputation: 1349

Please read man of read

As of

Also if I call the read() again, will it overwrite what is in the buffer? By that I mean empty the buffer and overwrite it with new input.

Well, read will overwrite the buff but not gone to empty buffer for you, you have to do it youself.

Upvotes: 1

Alan Stokes
Alan Stokes

Reputation: 18964

You're presumably using TCP, which is a streaming protocol - message boundaries are not sent, just the stream of bytes. So even if the server does a single write, you may end up having to do several reads to get the data.

Keep reading until either you have enough bytes, or read returns 0 (which means EOF).

If a read gets you N bytes, and it's not enough, then you need to issue another read targeting buffer + N.

Upvotes: 3

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The read(int fd, void *buffer, size_t count) function will read up to count bytes from file descriptor fd into buffer, so if there are only 10 bytes for reading it will only read 10 bytes. And no, it will not empty buffer and overwrite it's content, it will just overwrite the bytes read from the file descriptor.

Upvotes: 0

Related Questions