I want to write a buffer filled with BUFF_SIZE
bytes over a TCP socket using the write system call:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
The documentation states that
write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.
Of course, the number of actual bytes written can be detected by the return value. However, if I want to ensure that my whole buffer of bytes gets sent over the connection, what would be a good way to do this? So far, I was thinking:
while ( (ch = fgetc(pipe) ) != EOF )
{
buff[ 0 ] = ch;
bytes_in_buff++;
// fill a buffer's worth of data from the pipe
for (int i = 1; i < BUFF_SIZE; ++i, ++bytes_in_buff)
{
if ( (ch = fgetc(pipe) ) == EOF)
break;
buff[ i ] = ch;
}
// write that buffer to the pipe
int bytes_sent = 0;
while (bytes_sent < BUFF_SIZE)
{
bytes_sent = write(fd, buff, bytes_in_buff);
}
}
But of course, some redundant bytes will be sent if I continue to send the entire buffer each time bytes_sent < BUFF_SIZE
.