Re: data gets corrupted (c sockets)

From: David F
Date: Mon Jun 14 2010 - 15:58:10 EST

Al Lanot wrote:
Yes, I've checked this before (and now again) and even tried to change
to open/read functions
to handle the file, but that's not the problem.

Remember that I said that wget can download the files just fine though.

On Mon, Jun 14, 2010 at 9:02 AM, Roel van Meer <rolek@xxxxxxxxxx> wrote:
Al Lanot writes
My code is basically a modification of the one provided on this link ( )
which has the same problem as well.

The code to send the data is basically the following (it's my
modification but the original has the same problem) :

while(ftell(file) < length){
rbytes = fread(buf,1,sizeof(buf),file);
sbytes = write(newsockfd,buf,rbytes);
There are some problems in this code, and it is also incomplete.

Mistakes: you forgot to check for error return-codes from fread() and write().
Missing: you don't give the declaration of "buf". Or what is in "length".

I also echo Roel's comment regarding fread() -- if possible, I recommend using read() and write() -- amongst other advantages, it will be more efficient. You should also wrap your write() call into a loop in case it only wrote a partial buffer. This is again a problem of not checking the return-codes.

I furthermore recommend _not_ using ftell() to end your loop -- just loop until you reach EOF as indicated by a partially-filled (or 0-length) read (regardless of using fread() or read()). If you really want to stop the loop when you've reached the length that you expect, regardless of EOF status, keep your own counter of how many bytes you've sent.

The issue with wget() working could indicate many things, but not likely that the problem is on the other side -- perhaps it sends some different headers that don't trigger the bug.

Anyhow, you really should post the entire code. It's hard to say what the problem is when one only has a fragment of the code to look at.

-- David Favro

To unsubscribe from this list: send the line "unsubscribe linux-net" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at