No need to press ENTER to read input key value under Linux

Source: Internet
Author: User

Linux common input functions scanf and fgets are usually blocked:

1, if the user does not enter, the program will block waiting for the user input input, and require the user to enter the key to complete reading keyboard input.

2, the user input information, will be displayed on the screen.

The following code implements:

1, the user does not enter, then after the set time, the program will continue to run

2, the user input information will not be displayed on the screen

3, the program can not wait for carriage return, direct response to keyboard input

The code is as follows:

#include <stdio.h> #include<stdlib.h>#include<unistd.h>#defineTty_path "/dev/tty"#defineStty_us "STTY raw-echo-f"#defineStty_def "Stty-raw echo-f"#defineUnused_paramter (x) (void) (x)Static CharGet_char (void) {Fd_set RfDs; structTimeval TV; CharInput_char =0; Fd_zero (&RFDS); Fd_set (0, &RFDS); /** * Set wait time*///tv.tv_sec=0; Seconds//tv.tv_usec= -; Microseconds/*Check for keyboard input.*/    if(Select(1, &rfds, NULL, NULL, &AMP;TV) >0) Input_char=GetChar (); returnInput_char;} CharNonblocking_input (void ){    CharInput_char;    System (Stty_us Tty_path); Usleep (1xx); Input_char=Get_char ();    System (Stty_def Tty_path); returnInput_char;} intMainintargcChar**argv)    {Unused_paramter (ARGC);    Unused_paramter (argv); CharInput_char; Input_char=Nonblocking_input ();

printf ("\n\tyour input is%c!\n", Input_char);
printf ("\napplication finish.\n\n");

Return0;
}

No need to press ENTER to read input key value under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.