【发布时间】:2014-02-10 06:44:54
【问题描述】:
只是试图寻求理解。我正在编写一个小程序,它将从键盘读取击键事件,并触发某些事件(使用 switch 语句)。我正在做一些假设,并尝试将键盘视为要读取的 txt 文件。
我对最简单的方法感到不知所措。
我想要做什么打开文件(键盘事件 4),并使用 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?