문제

I'm developing very simple ftp client. I have created a data connection sockets, but I can't transfer file successfully:

FILE *f = fopen("got.png", "w");
int total = 0;
while (1){      
    memset(temp, 0, BUFFSIZE);
    int got = recv(data, temp, sizeof(temp), 0);

    fwrite(temp, 1, BUFFSIZE, f);
    total += got;

    if (total == 1568){
    break;
    }
}
fclose(f);

BUFFSIZE = 1568

I know that my file is 1568 bytes size, so I try to download it just for a test. Everything is file when I try to download .xml or .html files, but nothing good happens when I try to download png or avi files. Simply original file size is 1568 but got.png file size is 1573. I can't figure out what might cause that.

EDIT:

I have modified my code, so now it looks like (it can accept any file size):

FILE *f = fopen("got.png", "w");
    while (1){
        char* temp = (char*)malloc(BUFFSIZE);
        int got = recv(data, temp, BUFFSIZE, 0);

        fwrite(temp, 1, got, f);

        if (got == 0){
            break;
        }
    }
    fclose(f);

Still received file is 2 bytes too long.

도움이 되었습니까?

해결책

You are opening the file in text mode, so bare CR/LF characters are going to get translated to CRLF pairs when written to the file. You need to open the file in binary mode instead:

FILE *f = fopen("got.png", "wb");

다른 팁

You are always writing a whole buffer even if you have received only a partial one. This is the same problem with ~50% of all TCP questions.

The memset is not necessary. And I hope that temp is an array so that sizeof(temp) does not evaluate to the native pointer size. Better use BUFFSIZE there as well.


Seeing your edit, after fixing the first problem there is another one: Open the file in binary mode.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top