Search code examples
cfileftp-clientvxworks

why is this not writing (receiving) the correct number of Bytes?


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?


Solution

  • 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.