Could not transfer file using socket. Rather, the file is transmitted, but always of a different size. Here is the code snippet to send:

FILE *inFile = fopen(this->FullDir, "r+b"); //FILE *outFile = fopen(this->DeskDir, "w+b"); if (inFile != 0) { char* buffer[16384]; //выделяем блок 16Кб while (!feof(inFile)) //пока не конец файла { fread(buffer, 1, sizeof(buffer), inFile); //копируем блок send(s, (char*)&buffer, sizeof(buffer), 0);//передаём блок } } 

And for reception, respectively:

  do { msg_len = recv(new_client_socket, (char*)&buffer, MAX_MESSAGE_LENGTH, 0); fwrite(buffer, 1, sizeof(buffer), output); } while (msg_len > 0); 

The file size is 2.50 MB, it always comes in different ways from 1 MB to 2.2 MB. Where is the error?

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

Look at least

 char* buffer[16384]; 

Why do you need an array of pointers ? Next, you try to read sizeof(buffer) bytes, but how much do you actually read? Do you really have a file size that is strictly a multiple of sizeof(buffer) ?

I would act like this to begin with -

 char buffer[16384]; //выделяем блок 16Кб int readed; while((readed = fread(buffer, 1, sizeof(buffer), inFile)) != 0) { send(s, (char*)buffer, readed, 0); } 

and at the reception

 do { msg_len = recv(new_client_socket, (char*)buffer, sizeof(buffer), 0); fwrite(buffer, 1, msg_len, output); } while (msg_len > 0); 

Well, and would add a code of handling of errors of sending-receiving.

    The send function may send less data than requested. The actual number of bytes sent can be determined by the return value (can also return a negative number in case of errors).

    Also here:

    char * buffer [16384]; // select the block 16Kb

    the size of the array will most likely be 65536 bytes (for 32-bit systems), since an array of pointers to char is declared (probably char buffer [16384] implied).

    And here, in the file reception cycle:

    fwrite (buffer, 1, sizeof (buffer), output);

    the full size of the buffer will be written to the file, no matter how many bytes have come.