Reputation: 147
I would like to read from stdin until I reach end of file and then write that to a socket.
When I do this I don't want to read all of the data and then after reading, write to the socket.
It should be: read a byte of data, write that to the socket, read another byte, write that to the socket, etc. until I reach end of file.
Here is what I have so far:
char *buffer[65535];
while (read(0, buffer, 65535) > 0) {
write(sock, buffer, 65535);
}
sock is the socket file descriptor. I just used 65535 because somewhere I read that it was the max you can read() in.
How does this look?
Upvotes: 0
Views: 79
Reputation: 754880
How does this look?
Answer: a little buggy.
Just because you request 64KiB data doesn't mean you're going to get 64KiB of data. You need to record how much data you did receive, and only write what you read. Hence (noting the change of type for buffer
mentioned by WhozCraig in his comment):
char buffer[65536];
int nbytes;
while ((nbytes = read(0, buffer, sizeof(buffer))) > 0)
{
if (write(sock, buffer, nbytes) != nbytes)
{
…process short write…
}
}
There are several ways to process a short write. One is to capture the number of bytes actually written, and keep looping until all the data read has been written. The loop below would replace all of the if (write(…)…)
code.
Warning: untested code!
int nleft = nbytes;
int nwritten;
char *start = buffer;
while (nleft > 0 && (nwritten = write(sock, start, nleft)) > 0)
{
nleft -= nwritten;
start += nwritten;
}
if (nwritten < 0)
…process error…
Or you can simply report an error and abandon the writing process, which is much simpler but not as resilient.
Upvotes: 3