Search code examples
csocketsnewlinesystem-callsfgets

fgets unpredicted behavior after reading '\n'


Trying to code echo server\client in C, based on sockets. I can't understand how fgets() works for sure.

If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

 while (fgets(sendline, MAXLINE, stdin) != NULL) {
  sendline[strlen(sendline)-1] = '\0';
  send(sockfd, sendline, strlen(sendline), 0);}

But what I get on server:

String received from and resent to the client:1234567890

String received from and resent to the client:abc
567890

as you can see, '\n' char added to second line, and tries to override first, with new line. But on client, I see that buffer have no '\n' while use send().

Hitting ctld+D (EOF) works as expected.

How to prevent this? And send using Enter key?

This picture expain what I mean. And there is no change after comment certain lines of code (for @PCLuddite) enter image description here


Solution

  • Certainly the receiving end is not forming a string, just an array of char with no null character. Send a +1 to include the null character. @milevyo

    while (fgets(sendline, sizeof sendline, stdin) != NULL) {
      size_t length = strlen(sendline);
      if (length > 0 && sendline[length-1] == '\n') {
         sendline[--length] = '\0';
      }
      send(sockfd, sendline, length + 1, 0);  // + 1
    }