检查stdin是否为空

51k*_*51k 8 c c++ stdin

我搜索但没有得到这个问题的相关答案,我正在使用linux机器,我想检查标准输入流是否包含任何字符,而不从流中删除字符.

Cac*_*nta 6

您可能想尝试select()函数,并等待将数据输入到输入流中.

描述:

select()和pselect()允许程序监视多个文件描述符,等待一个或多个文件描述符变为"准备好"某些类的I/O操作(例如,输入可能).如果可以在不阻塞的情况下执行相应的I/O操作(例如,读取(2)),则认为文件描述符就绪.

在您的情况下,文件描述符将是 stdin

void yourFunction(){
    fd_set fds;
    struct timeval timeout;
    int selectRetVal;

    /* Set time limit you want to WAIT for the fdescriptor to have data, 
       or not( you can set it to ZERO if you want) */
    timeout.tv_sec = 0;
    timeout.tv_usec = 1;

    /* Create a descriptor set containing our remote socket
       (the one that connects with the remote troll at the client side).  */
    FD_ZERO(&fds);
    FD_SET(stdin, &fds);

    selectRetVal = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);

    if (selectRetVal == -1) {
        /* error occurred in select(),  */
        printf("select failed()\n");
    } else if (selectRetVal == 0) {
        printf("Timeout occurred!!! No data to fetch().\n");
        //do some other stuff
    } else {
        /* The descriptor has data, fetch it. */
        if (FD_ISSET(stdin, &fds)) {
            //do whatever you want with the data
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

  • 但是,感谢一瞬间,我不想等待输入流拥有数据,只是如果流有数据,我需要做一些处理,如果它没有数据,做其他一些处理.代码不应该等待输入, (3认同)

aut*_*tic 5

cacho在正确的路径上,但是select只有在处理多个文件描述符时才有必要,并且stdin不是POSIX文件描述符(int); 这是一个FILE *.STDIN_FILENO如果你走这条路,你会想要使用.

这也不是一条非常干净的路线.我更喜欢使用poll.通过指定0作为timeout,poll将立即返回.

如果在任何选定的文件描述符上都没有发生任何定义的事件,则poll()应至少等待超时毫秒,以便在任何选定的文件描述符上发生事件.如果timeout的值为0,则poll()应立即返回.如果timeout的值为-1,则poll()将阻塞,直到发生请求的事件或者直到调用中断为止.

struct pollfd stdin_poll = { .fd = STDIN_FILENO
                           , .events = POLLIN | POLLRDBAND | POLLRDNORM | POLLPRI };
if (poll(&stdin_poll, 1, 0) == 1) {
    /* Data waiting on stdin. Process it. */
}
/* Do other processing. */
Run Code Online (Sandbox Code Playgroud)