C Socket file transfer corrupted data
<p>According to <a href="https://stackoverflow.com/questions/20314524/c-opencv-image-sending-through-socket/20321262#20321262">this solution</a> to send out an image through TCP. Since the code is very elegant compared to other ways and both image and file are data, I believe that we can use almost the same code to send out a file. </p>

<p>So if I want to send a file from a client to a server.</p>

<p>On the <strong>client</strong> side </p>

<ol>
<li>get file size </li>
<li>send file size
// Above steps will always work, so I will only show code after here</li>
<li><p>read file content into a buffer</p>

<pre><code>char buf[size];
read(fs,buf,size);
</code></pre></li>
<li><p>send the buffer</p>

<pre><code>int bytes = 0;
for (uint i = 0;i&lt;size;i+=bytes)
{
    if ((bytes = send(sock,buf+i,size-i,0))&lt;0)
    {
        fprintf(stderr,"Can not send file\n");
        close(fd);
        return false;
    }
    fprintf(stderr,"bytes write = %d\n",bytes);
}
</code></pre></li>
</ol>

<p>And on the <strong>server</strong> side</p>

<ol>
<li>recv file size</li>
<li><p>recv stuff into a buffer with size from step 1</p>

<pre><code>char buf[size];
int bytes=0;
for (uint i = 0;i&lt;size;i+=bytes)
{
    if ((bytes = recv(sock,buf+i,size-i,0))&lt;0)
    {
        fprintf(stderr,"Can not receive file\n");
        return false;
    }
    fprintf(stderr,"bytes read = %d\n",bytes);
}
</code></pre></li>
<li><p>write buffer to a file</p>

<pre><code>fwrite(buf,sizeof(char),size,fs);
</code></pre></li>
</ol>

<p>This code will compile and run. </p>

<p>When I send out an cpp binary file(24k) from client to server, since both client and server are on the same machine (OS X), this binary file will be received and can be executed. </p>

<p>But if the server forward the file back to the client, and client forward this file back to the server multiple times, this binary file will be corrupted. But the number of bytes sent and number of bytes received are the same, and the file size is still 24k. </p>

<p>I am wondering what is going wrong here.</p>

<p>Is this an OS bug?</p>

<p>Thanks,</p>