Question

I am writing a program for transferring files between different clients and i have a little problem.

I ran to an example where it doesn't work.

I have a pdf file and i am reading it using fread:

bytes = fread(chunk, 1, BUFLEN - 1, from_file);

After a bit of debugging i found out that this line of code does not read BUFLEN - 1 bytes (oh by the way, the file is big and i am iterating only once to take the first BUFLEN - 1 bytes, so the file has more than BUFLEN - 1 bytes). The return value of fread is actually BUFLEN - 1, but after writing this chunk to a file it has a much smaller size.

I suppose fread stops reading when running into something, but i couldn't find out what.

I opened the file with "rb" so this isn't the problem either. Moreover, my program seems to read well any text files, of any size, and this is the reason i believe it has some problems when finding different type of bytes.

EDIT: I am sending the chunk via

    send(socksv, chunk, strlen(chunk), 0);

In receive:

    n = recv(i, chunk, BUFLEN - 1, 0);

After that i write it like this

    fwrite(chunk, 1, strlen(chunk), copy_file);
Was it helpful?

Solution

The problem is almost certainly the use of strlen() as this will stop writing (either to the socket or to the file) when it sees a zero-byte, which there almost certainly will be inside the PDF. You need to be remembering the size of the chunk (as returned by fread()) and use this for your writes.

Also, make sure you're checking the return value of send() as it can send only part of the buffer you ask it to.

OTHER TIPS

If the file is in binary mode and fread() says it read BUFLEN-1 bytes then it really did. You say you are writing the read data to another file, so the problem has to be with your writing, not your reading. You did not show that code, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top