transfer file using recv() and fwrite()

Discussion in 'C Programming' started by michelle, Jun 26, 2003.

  1. michelle

    michelle Guest

    Hi, I am trying to transfer a binary file from a client program to the
    server, so on the server side I am using recv() to receive the binary
    data to the buffer and then write to a file. The follwoing is my
    code. Somehow, the newly transfered file is different from the
    original file. I don't know if the error is at recv() or fwrite().
    For receving, I already check that the bytes being sent equals to the
    btyes being received. So anyone knows what's wrong with my code?
    Thanks.

    char buf[length]; (length is how many bytes of data)
    fid=fopen("dataio_testing.bit", "wb"); (open a file to write binary
    data)
    //this part is right, coz it receive right amount of bytes.
    while (bytes != length) {
    bytes += recv(clisock, buf, length-bytes, 0);

    }

    num=fwrite(buf, 1, bytes, fid); (write data into file, in unit of
    bytes)
    fclose(fid);
     
    michelle, Jun 26, 2003
    #1
    1. Advertisements

  2. Depending on the size of the data and the size of the messages, it could
    happen that you receive multiple messages. The recv() function returns
    the number of bytes received so that adds up nicely to the amount of bytes
    you expect, but you store all messages at the start of the buffer
    (overwriting older messages with newer ones.) You could use the number of
    bytes received as an offset in the buffer for new messages.

    Regards,
    Rob van der Leek
     
    Rob van der Leek, Jun 26, 2003
    #2
    1. Advertisements

  3. michelle

    michelle Guest

    Hi, Rob. Your solution is right, that solves the problem in seconds
    verse I was trying to debug whole day yesterday. Thank you very
    much!!!!

    Michelle

     
    michelle, Jun 26, 2003
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.