Closing then opening standard input in C under Linux -


i have c console application under linux (raspbian - raspberry pi). program has character animation - prints out messages character character. example, text

please give me name!

is printed out after 5 seconds (char char).

afterwards, user asked type in name, works fine if user waits message printed out. however, if user impatient , hits keys on keyboard randomly, input request later compromised.

imagine user types in

abc\nefgh\n

while above text being echoed ('\n' means new line - enter). if happens, user not asked type in his/her name, array of characters 'abc' accepted input , gets validated.

my question how disable input (buffering) temorarily (on linux). have tried several methods , read numerous posts doing so, none of them worked purpose.

the function responsible asking input follows:

int getline(char *s, int length) {     int i;     char c;      (i = 0; < length && (c = getchar()) != eof && c != '\n'; i++)     {         if (c == '\0')         {             i--;         }         else         {             s[i] = c;         }     }      s[i] = '\0';      while (c != eof && c != '\n')     {         c = getchar();     }      return i; } 

empty lines eliminated of while loop in function calling 1 above enter inputs considered invalid.

i tried closing stdin, not reopen it:

fclose(stdin); 

and emptying buffer before getline:

char buf[bufsiz]; while (c = fgets(buf, bufsiz, stdin) != null); 

unfortunately, did not work text files.

fflush(stdin); did not work either , not pretty anyway.

my goal prevent users typing in while text being written out , ignore/close input buffering (stdin) temporarily. also, great disable outputting (flushing) user inputs during printing gets displayed on linux terminal.

you may interacting tty directly. source code of passwd or similar utilities inspiration.

function below clears tty input buffer (error handling omitted). need call before reading user input.

#include <sys/ioctl.h> #include <termios.h>  void clear_user_input() {   if (isatty(stdin_fileno)) {     int fd = open(ttyname(stdin_fileno), o_rdonly);     ioctl(fd, tcflsh, tciflush);     close(fd);   } } 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -