문제

I receive data from an ftp socket connection. The connection seems tio be fine but for some reason, I don't get the correct nmumber of Bytes written to my destination file. My source file has a size of 18735004 Bytes and my algorithm writes 19713024 Bytes to the file. Now can this be? The code I have:

if (ftpXfer ("3.94.213.53", "**", "******", NULL,
             "RETR %s", "/home/ge", "ngfm.bin",
             &ctrlSock, &dataSock) == ERROR)
    return (ERROR);

pFile = fopen( "flash:/ngfm.bin", "wb" );
if ( pFile == NULL ) {
    printf("fopen() failed!\n");
    status = ERROR;
}

while ((nBytes = read (dataSock, buf, sizeof (buf))) > 0) {
    cnt++;
    n+=fwrite (buf , sizeof(char), sizeof(buf), pFile);
    if(cnt%100==0)
        printf(".");
}
fclose( pFile );
printf("%d Bytes written to flash:/ngfm.bin\n",n);

The screen output ended with:

19713024 Bytes writen to flash:/ngfm.bin

What's wrong here?

도움이 되었습니까?

해결책

You are ignoring the nBytes return value from read(), and instead always writing sizeof buf bytes to the output. That's wrong, for partial reads (where nBytes is less than sizeof buf) you are injecting junk into the written stream.

The write should of course use nBytes, too.

Also: the write can fail, and write less than you requested, so you need to loop it until you know that all bytes have been written, or you get an error from it.

다른 팁

It seems you aren't putting your FTP server in binary mode, and it's transferring in ascii. This replaces every \n with a \r\n sequence.

Additionally, unwind's reply is correct as well.

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