我正在写一个小套接字程序(GNU libc)。 我有一个循环,要求用户input(例如“MSG>”)。 当用户按下input消息发送(当前到localhost上的服务器)。
无论如何,我想从stdin读入char缓冲区[256]。 我目前正在使用fgets()这不是我想要的。 我不知道如何编写代码,以便我问用户,然后一次获取数据256 -1字节,以便我可以通过多个256字节的string发送一个1000字节的Cstring。
编辑:添加代码
#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
的返回值小于零时,你应该担心。 确保你处理这些情况。
这个怎么样:
fread(buffer, sizeof(buffer), 1, stdin);
如果您使用的是fgets()
,则使用标准IO库。 您将要使用fread()
然后(而不是使用文件描述符的read()
)来指定要读取的字节数。 请参阅: http : //www.cplusplus.com/reference/cstdio/fread/
您可以考虑使用read
功能进行缓冲输入。 它需要一个打开的文件描述符(stdin的STDIN_FILENO),一个指向缓冲区( char *
)的指针以及要读取的字节数。 请参阅手册条目了解更多详情。