C - Read Directly From the Keyboard Buffer

2019-04-10 11:27发布

问题:

This is a question in the C programming language.

How do I directly read the data in the keyboard buffer?

I want to directly access the data and store it in a variable. Of what data type should the variable be?

I need it for an operating system our institute is currently developing. It's called ICS-OS and I am not quite sure about the specifics. It runs on x86, 32-bit machines (we run it on QEMU in a Linux box). Here is the link for the Google Code http://code.google.com/p/ics-os/. I hope that's sufficient enough information.

The operating system does not support the conio.h library so kbhit is not an option.

回答1:

This is really platform dependent.

If this is for Windows, the most direct access to a "keyboard buffer" is using WM_INPUT and GetRawInputData. See Using raw input with example for both keyboard and mouse.

Another DOS / Windows specific way are conio.h functions getch() / kbhit().

Portable library is called Curses and has ports for both Linux and Windows.

However, as you are targeting quite specific OS, you need to check the docs for that OS.

The most direct platform independent way is getchar / scanf / anything which reads from stdin, but stdin is line buffered, therefore you will get no data until enter is pressed. You may be able to change the buffering settings, but again, this is platform dependent and may be not possible on some platform. See a related discussion of setbuf(stdin,NULL).



回答2:

Have you tried looking at the source code of the linux kernel for the keyboard driver? Take a look at /drivers/input/keyboard/xtkbd.* for a simple XT keyboard driver.

Also, here's an article which briefly explains how it's done.



回答3:

if you want to directly read data from keyboard buffer then you can user getchar or getc!



回答4:

This is read from keyboard buffer

scanf("%d",&myvariable);

but you have to use "%d" for int ,"%f" for float ,%e for double ,"%c" for char , "%s" for strings to identifing type which has to match type of your variable.