试图寻求理解。我正在编写一个小程序,它将从键盘读取按键事件,并触发某些事件(使用switch语句)。我正在做一些假设,并试图把键盘当作一个txt文件来读取。在C中使用系统调用来读取键盘事件
对于最简单的方法来说,我有点不知所措。
我想要做的事情是打开文件(键盘event4),然后使用类似fgets的东西在无限循环中逐个字符地读取它,然后使用switch语句打破循环并退出。
我被卡住的地方在于这些是系统调用,而我基本上不确定如何处理它们。
下面的代码绝对不会编译,只是把它放在那里作为我试图做的粗略演示。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
// errors on opening
int fd = open("/dev/input/event4", O_RDONLY);
if(fd < 0)
{
printf("error while opening/n");
return 1;
}
int keystroke = 0;
while (1)
{
keystroke = fgetsc(fd);
switch(keystroke)
{
case '1' :
break;
case '2' :
break;
case '3' :
break;
default:
printf("waiting for 1, 2, 3/n");
}
close(fd);
return 0;
}
为什么不使用'read(0,...)'来读取'stdin'? – Ilmirus