检查标准输入是空的 [英] Check if stdin is empty

查看:187
本文介绍了检查标准输入是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜查,但没有得到相关回答这个问题,我工作在Linux机器上,我想检查标准输入流中包含的任何字符,但不从流删除字符。

I searched but did not get a relevant answer to this question, i am working on a linux machine, i wanted to check if the standard input stream contains any character, without removing the characters from the stream.

推荐答案

您可能会想尝试的选择()函数,并等待其数据到输入流。

You might want to try select() function, and wait for having data into the input stream.

说明:

选择()并PSELECT()允许程序监视多个文件
  描述符,等待,直到一个或多个文件描述符成为
  准备好了对一些类的I / O操作(例如,输入可能)的。一份文件
  描述符被认为是准备好,如果它是能够进行
  相应的I / O操作(例如,读取(2))不阻塞。

select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking.

在你的情况,文件描述符将标准输入

In your case, the file descriptor will be 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
        }
    }
}

希望它帮助。

这篇关于检查标准输入是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆