How to receive full text in a text file into server in c?

Ryan Thompson Source

I tried to implement the STOR command with text files. In the server I have code that receives files as string into the receive_buffer. Is there a way I could receive the string as a whole string into the buffer?

            while (true)
                if (active == 0) 
                    bytes = recv(ns_data, receive_buffer, strlen(receive_buffer), 0);
                    recv(s_data_act, receive_buffer, strlen(receive_buffer), 0);
                    printf("len: %d\n", strlen(receive_buffer));
                    printf("receive_buffer: %s\n", receive_buffer);

                printf("Receive_buffer: %s\n", receive_buffer);

                strcpy(temp_buffer, receive_buffer);
                printf("temp_buffer: %s\n", temp_buffer);
                fputs(temp_buffer2, f);

At the moment, say for example there is a text file called text.txt and sample text in side "this is a word", the recv function only gets 4 characters at a time. So on the first loop it would get "this", on the second it would get " is ", and so forth. How can I just get the whole string into the receive buffer and terminate it when there is no more text in the file that it is reading from?



answered 5 months ago sudo #1

recv the way you're using it will read until there's no more data in the socket's buffer or your receive buffer is full, causing the behavior you see. There's no way to know when the file is done being received unless you build that into your protocol.

If the file is text only, you could terminate messages with a 0 byte (\0) and call recv repeatedly until you see that arrive (since \0 won't be in any text file). Or you could prepend all transmissions with a special header indicating the length. Both ways are unsafe if you aren't very careful.

comments powered by Disqus