Checking the stdin buffer if it's empty

前端 未结 4 1560
名媛妹妹
名媛妹妹 2020-12-01 22:18

I am trying to read a number character with character, but I don\'t know if the stdin buffer is empty or not.

My first solution whas to look for \'\\n\' character i

4条回答
  •  鱼传尺愫
    2020-12-01 22:24

    For anyone who comes here from google – easy select solution to check stdin emptyness:

    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);
    fd_set savefds = readfds;
    
    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 0;
    
    int chr;
    
    int sel_rv = select(1, &readfds, NULL, NULL, &timeout);
    if (sel_rv > 0) {
      puts("Input:");
      while ((chr = getchar()) != EOF) putchar(chr);
    } else if (sel_rv == -1) {
      perror("select failed");
    }
    
    readfds = savefds;
    

    Needs unistd.h, stdlib.h and stdio.h.

    Explanation can be found here.

    UPD: Thanks DrBeco for noticing that select returns -1 on error -- error handling was added.

    Actually, select returns:

    • the number of ready descriptors that are contained in the descriptor sets
    • 0 if the time limit expires
    • -1 if an error occurred (errno would be set)

提交回复
热议问题