I need a function that immediately returns either a character existing in the keyboard buffer or a -1
This so I can qualify input before it is echo-ed to the console display.
I found this code but it mysteriously echos characters to the console and I can't figure out why:
Thanks for your help
This so I can qualify input before it is echo-ed to the console display.
I found this code but it mysteriously echos characters to the console and I can't figure out why:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int input;
int flags = fcntl(STDIN_FILENO, F_GETFL, 0); // Get the current file status flags
if (flags == -1) {
perror("fcntl");
return 1;
}
// Set the non-blocking flag
flags |= O_NONBLOCK;
if (fcntl(STDIN_FILENO, F_SETFL, flags) == -1) {
perror("fcntl");
return 1;
}
while (1) {
char c;
int bytesRead = read(STDIN_FILENO, &c, 1); // Try to read one character
if (bytesRead == 1) {
printf("Character in buffer: %c\n", c);
}
// Your other code here (non-blocking)
input = getchar(); // Read a single character and do nothing with it, however, It still gets "Printed"
}
return 0;
}