首页 文章

C - 一次从stdin BUFSIZE字符读取

提问于
浏览
2

我正在编写一个小套接字程序(GNU libc) . 我有一个循环,要求用户输入(例如“MSG>”) . 当用户按下enter时,将发送消息(当前发送到localhost上的服务器) .

无论如何,我想从stdin读入char缓冲区[256] . 我目前正在使用fgets(),它不能满足我的需求 . 我不确定如何编写代码,以便我询问用户然后一次获取256个字节的数据,这样我就可以通过几个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;
}

4 回答

  • 1

    如果您正在使用 fgets() ,那么're using the standard IO library. You'将要使用 fread() (而不是使用文件描述符,而不是 read() )来指定要读取的字节数 . 见:http://www.cplusplus.com/reference/cstdio/fread/

  • 2

    这个怎么样:

    fread(buffer, sizeof(buffer), 1, stdin);
    
  • 1

    您可以考虑将 read 函数用于缓冲输入 . 它需要一个打开的文件描述符(stdin的STDIN_FILENO),一个指向缓冲区的指针( char * )和要读取的字节数 . 有关详细信息,请参见手册entry .

  • 1

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

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

相关问题