gpt4 book ai didi

c++ - C - 一次从标准输入读取 BUFSIZE 个字符

转载 作者:太空狗 更新时间:2023-10-29 11:38:38 24 4
gpt4 key购买 nike

我正在编写一个小型套接字程序 (GNU libc)。我有一个循环要求用户输入(例如“MSG>”)。当用户按下回车键时,消息被发送(当前发送到本地主机上的服务器)。

无论如何,我想从标准输入读取到字符缓冲区[256]。我目前正在使用 fgets() ,它不符合我的要求。我不确定如何编写代码,以便我询问用户,然后一次获取 256 -1 字节的数据,以便我可以通过多个 256 字节的字符串发送 1000 字节的 c 字符串。

编辑:添加代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFSIZE 256

int main(int argc, char *argv[])
{
char msg[BUFSIZE];
size_t msgLen;

msgLen = strlen(fgets(msg, BUFSIZE, stdin));
puts(msg);

// This simply checks whether we managed to fill the buffer and tries to get
// more input
while (msgLen == (BUFSIZE - 1))
{
memset (msg, '\0', BUFSIZE);
fread(msg, BUFSIZE, 1, stdin);
msg[BUFSIZE - 1] = '\0';
msgLen = strlen(msg);
puts(msg);
if (msgLen < (BUFSIZE - 1))
break;
}

return 0;
}

最佳答案

您正在实现一个循环以确保收到 1000 个字节,对吗?为便于阅读,循环应指示它计数到 1000。跟踪您读取的字节数(使用 += 运算符),并在循环条件中使用该数字。

您似乎假设 fread 将读取 255 个字节,但这是在 255 个字节可用的无效假设下。当读取少于 255 个字节时,这并不一定表示错误;继续阅读!当 fread 的返回值小于零时,您就应该担心了。确保你能处理这些情况。

关于c++ - C - 一次从标准输入读取 BUFSIZE 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14553868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com