3

I'm doing a super simple ftp server for class in C++, Client: Read from a file write in the socket. server: Read from socket write on file. I have finished all the networking and everything works but ofstream.write has a very odd behavior: It doesn't write the last packet that is smaller than 1024byte.

I have tried changing the last buffer size so that it would be the number of byte read, I have tried looking at the error flags but none occured yet nothing was written, I have tried writing 1024 byte, I does write but there is trash at the end (^@ chars).

private:
    ofstream &out_stream;

for (;;)
{
    nread = recvfrom(sfd, buf, 1024, 0, (struct sockaddr *)&peer_addr, &peer_addr_len);
    out_stream.write(buf, nread);
    if (nread < 1024)
        break;
}

The written file should contain 1687 bytes but contains only 1024 bytes and if I try out_stream.write(buf, 1024); it contains 2048 bytes. I checked that the programs goes twice in the loop as it should, so the condition is not the problem.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
Emanone
  • 31
  • 1
  • 2
    Have you tried a `out_stream.flush();` after the `for` loop? I'm asking this because from your exposed code, it's not clear when the `out_stream` is closed or destroyed (which would automatically flush() the still buffered contents). – Scheff's Cat May 27 '19 at 11:05
  • Possible duplicate of [How does std::flush work?](https://stackoverflow.com/questions/14105650/how-does-stdflush-work) – L. F. May 27 '19 at 12:42

0 Answers0