How can I prevent scanf() to wait forever for an input character?

前端 未结 5 2142
悲哀的现实
悲哀的现实 2020-12-01 16:56

I want to fulfill the following things in a console application:

  1. If user inputs a character, the application will do the corresponding task. For example, if us
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 17:06

    Try using the select() function. Then you can wait for 10 seconds until you can read from stdin without blocking. If select() returns with zero, perform the default action. I don't know if this works on windows, it's POSIX standard. If you happen to develop on unix/linux, try man select

    I just wrote a working example using select:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #define MAXBYTES 80
    
    int main(int argc, char *argv[])
    {
            fd_set readfds;
            int    num_readable;
            struct timeval tv;
            int    num_bytes;
            char   buf[MAXBYTES];
            int    fd_stdin;
    
            fd_stdin = fileno(stdin);
    
            while(1) {
                    FD_ZERO(&readfds);
                    FD_SET(fileno(stdin), &readfds);
    
                    tv.tv_sec = 10;
                    tv.tv_usec = 0;
    
                    printf("Enter command: ");
                    fflush(stdout);
                    num_readable = select(fd_stdin + 1, &readfds, NULL, NULL, &tv);
                    if (num_readable == -1) {
                            fprintf(stderr, "\nError in select : %s\n", strerror(errno));
                            exit(1);
                    }
                    if (num_readable == 0) {
                            printf("\nPerforming default action after 10 seconds\n");
                            break;  /* since I don't want to test forever */
                    } else {
                            num_bytes = read(fd_stdin, buf, MAXBYTES);
                            if (num_bytes < 0) {
                                    fprintf(stderr, "\nError on read : %s\n", strerror(errno));
                                    exit(1);
                            }
                            /* process command, maybe by sscanf */
                            printf("\nRead %d bytes\n", num_bytes);
                            break; /* to terminate loop, since I don't process anything */
                    }
            }
    
            return 0;
    }
    

    Note: the poll() example below is OK too, no problem. For the rest I chose to read the available bytes into a buffer (up to MAXBYTES). It can be (s)scanned afterwards. (scanf() just isn't too much my friend, but that's a personal taste matter).

提交回复
热议问题