c - 读取 '\n' 后 fgets 意外行为

标签 c sockets newline system-calls fgets

尝试基于套接字在 C 中编写 echo server\client。 我无法确定 fgets() 是如何工作的。

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);}

但是我在服务器上得到的是:

String received from and resent to the client:1234567890

String received from and resent to the client:abc
567890

如您所见,'\n' 字符添加到第二行,并尝试用新行覆盖第一行。但是在客户端,我看到缓冲区在使用 send() 时没有 '\n'。

按 ctld+D (EOF) 按预期工作。

如何预防?并使用 Enter 键发送?

这张图片解释了我的意思。注释某些代码行后没有变化(@PCLuddite) enter image description here

最佳答案

当然接收端不是组成一个字符串,只是一个没有空字符的char数组。发送 +1 以包含空字符。 @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
}

关于c - 读取 '\n' 后 fgets 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314299/

相关文章:

python urllib2请求在前面添加换行符来发布数据

C、socket编程: Connecting multiple clients to server using select()

java - 在 Java 中转发 HTTP 请求

javascript - 使用 Node.js FFI 绑定(bind)数据(javascript & c)

java - 将套接字转换为字符串,反之亦然

java - 如何在有限的时间内(超时)从 DatagramSocket 中读取数据 block ?

java - 将两个字符串与新行合并

java - BufferedWriter 没有在文件中为添加了 "\n"的字符串写入新行

c++ - 如果没有文件、objdump 或 gdb,如何知道二进制文件是否包含调试符号?

c - 在两个字符串(相同位置)中找到相同的字符并返回金额