2014-02-11 31 views
0

下面的代碼可能有幾個問題。在找到一種在linux中獲取鍵盤輸入的方式後在網上找到它。我已驗證鍵盤輸入的正確事件。對我來說似乎很腥的原因是無論我放在文件路徑中,似乎總是通過錯誤檢查(打開的調用返回大於0的東西)。有些東西顯然是錯誤的,所以建議是值得歡迎的。在Linux上使用C開放系統調用

這將無法正確運行,除非您運行該exe作爲su。

當我想讀取我的按鍵時,是否在無限while循環中使用類似fgets的文件描述符之類的東西?我希望它不斷地對鍵盤輸入進行輪詢。解碼鍵盤事件輸入的任何提示?

再次感謝!我的這個項目可能過於雄心勃勃,因爲我已經做了很長時間,因爲我已經完成了任何編碼。

#include <stdio.h> 
#include <stdlib.h> 
#include <stddef.h> 
#include <fcntl.h> 
#include <linux/input.h> 
#include <unistd.h> 

// Edit this line to reflect your filepath 

#define FILE_PATH "/dev/input/event4" 

int main() 
{ 
    printf("Starting KeyEvent Module\n"); 

    size_t file; //will change this to int file; to make it possible to be negative 
    const char *str = FILE_PATH; 

    printf("File Path: %s\n", str); 

    error check here 
    if((file = open(str, O_RDONLY)) < 0) 
    { 
     printf("ERROR:File can not open\n"); 
     exit(0); 
    } 

    struct input_event event[64]; 

    size_t reader; 
    reader = read(file, event, sizeof(struct input_event) * 64); 

    printf("DO NOT COME HERE...\n"); 

    close(file); 
    return 0; 
} 

回答

2

的問題是在這裏:

size_t file; 

的size_t是無符號的,所以它總是會> = 0

它應該是:

int file; 
+1

dangit ..認爲這是愚蠢的。 – user3287789

+0

+1,乾淨簡單的答案。並且,以@ user3287789爲+1,以如此優雅的方式使用_dangit_。 – ryyker

+0

我討厭優雅。不幸的是,它不會轉化爲代碼。現在想出投票部分。 – user3287789

0

開放調用返回的東西比0

open回報int更大,但你把在一個無符號的變量(size_t通常是無符號),所以你不能檢測時,它是<0

+0

是有道理的,應該抓住這一點。 – user3287789