試圖尋求理解。我正在編寫一個小程序,它將從鍵盤讀取按鍵事件,並觸發某些事件(使用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