recv()-ing 一个带有 "\0" 和 "\n" 的字符串

recv()-ing a String with "\0" and "\n" in it

所以编写了一个客户端,它只接收缓冲区中的字符,我随后打印出来:

//CODE FROM BJ'S GUIDE TO NETWORK PROGRAMMING *1
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
        perror("recv");
        exit(1);
    }

    buf[numbytes] = '[=10=]';

    printf("%s",buf);
//MY CODE
    while (numbytes > 0) {
        numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0);
        if (numbytes > 0) {
            buf[numbytes] = '[=10=]';
            printf("\%s",buf);
        }
    }

buf 是一个 char[512] 数组

我还想 recv() "\0" 和 "\n" 并将它们打印为 "\0" 和 "\n"

代码看起来像这样

printf("this contains a \n byte and a \0 byte");

我无法更改服务器端的内容,因为我必须编辑接收端

*1: https://beej.us/guide/bgnet/

I want to also recv() "[=12=]" and "\n" and print them out as "[=12=]" and "\n"

不要在 buf 上使用 string 函数。将其作为字符数组处理。

while (numbytes > 0) {
  numbytes = recv(sockfd, buf, MAXDATASIZE, 0);
  for (i = 0; i < numbytes; i++) {
    unsigned char ch = buf[numbytes];
    if (ch <= '\n') {  // Escape characters 0 to 13
      putc('\');
      putc("0123456abtrvfn"[ch]);
    } else if (ch == '\') {  // I suspect OP will also want this
      putc('\');
      putc('\');
    } else {
      putc(ch); 
    }
  }
}

好的,我们是这样使用 fwrite() 做到的

    fwrite(buf, numbytes, sizeof(char), stdout);