Take the 2-minute tour ×

Actually i'm working on very simple ftp server. Now i have problem with sending file (RETR in ftp protocol). I'm using sockets and binary mode in my client. Files with text sends perfectly but problem is binary files (images etc.).

Here's piece of my code:

FILE *fin=fopen(fileloc,"rb");

            if(fin != NULL){
                fpos_t filelen;

                fseek (fin, 0, SEEK_END);
                fgetpos (fin, &filelen);

                fseek (fin, 0, SEEK_SET);
                printf("Sending file %s (%d b)", fileloc, filelen);
                sprintf(sbuffer,"150 Opening BINARY mode data connection for file transfer.\r\n");
                bytes = send(ns, sbuffer, strlen(sbuffer), 0);
                byte temp_buffer[512];

                long int totalsent;
                totalsent = 0;

                while (!feof(fin)){

                    memset(temp_buffer, '\0', sizeof(sbuffer));

                    fgets((char *)temp_buffer, sizeof(sbuffer), fin);

                    if (!active) bytes = send(ns_data, (char *)temp_buffer, strlen(sbuffer), 0);
                    else bytes = send(s_data_act, (char *)temp_buffer, strlen(sbuffer), 0);

                    totalsent = totalsent + bytes;

                    printf("     file size = %d, send = %d bytes, strlen = %d, total = %d, left = %d\n", filelen, bytes, strlen(sbuffer), totalsent, filelen-totalsent);

                sprintf(sbuffer,"250 File transfer completed... \r\n");

My ftp client getting incoplete file with differences inside (i open files by notepad to compare). All You can see on this screen: http://i53.tinypic.com/2wcjtdk.jpg

There is also differences in file size - oryginal file is about 7kB and sent copy is about 1kB less. I used much different ftp client and there is same problem. I'm working 2 days at this problem, my cat have heat, please help!

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

In your send call you are using strlen which might work fine for text data but not for binary data. When you read from the file you need to use a call like read which will tell you how many bytes were actually read so you can send that many bytes in the send call.

share|improve this answer
To clarify: Essentially the problem with using fgets and strlen is that you are losing all the null bytes in a binary file, since a null byte is used to terminate strings. It works fine for text files because they generally do not include null bytes. –  PleaseStand Dec 28 '10 at 23:19
Guys thank You. I just solved this problem thanks to Your tips. –  Bury Dec 28 '10 at 23:38
add comment

Your Answer


