0

I have the following snippet where I read sent bytes usingread() and store the data in a buffer which works well. But how do i make it so that I can continue to write in binary file after every read. My assumption is that it might have something to do with not resetting the buffer. Thanks for the help!

fp = fopen (filename, "wb"); //create a file

while (size > 0){        
    n = read(socket,buffer,size*sizeof(char));
    if (n <=0)
        return -1;
    p += n;
    size -= n;

    fwrite(buffer,sizeof(char),size*sizeof(char),fp); //write the content to the file

}
1
  • You shall proof fp if fopen() was successful. Commented Mar 14, 2020 at 9:46

1 Answer 1

1

You should use n in the call to fwrite(), not size. n is the amount you just read from the socket, size is how many more bytes you're still waiting for.

fwrite(buffer,sizeof(char),n,fp);

You also shouldn't multiply by sizeof there. The second argument is the size of each element, the third argument is the number of elements; fwrite() performs the multiplication internally. It happens to work in your case because sizeof(char) is always 1, so the multiplication didn't change anything.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this was the problem actually! Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.