我有一个模拟键盘的USB RFID读卡器.所以当我把卡片放到它上面时,我会看到终端窗口上的字符串-ie"0684a24bc1"
但我想在我的C程序中阅读它.我使用时没有问题:scanf("%s",buff);
但是,当我使用下面的代码时,我得到了很多(大约500字节)无法识别的数据.为什么?我想要非阻塞读取.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int main(int argc, char ** argv) {
int fd;
char buf[256];
fd = open("/dev/input/event3", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_port: Unable to open /dev/ttyAMA0 - ");
return(-1);
}
// Turn off blocking for reads, use (fd, F_SETFL, FNDELAY) if you want that
fcntl(fd, F_SETFL, 0);
}
while(1){
n = read(fd, (void*)buf, 255);
if (n < 0) { …Run Code Online (Sandbox Code Playgroud) 我有一个小程序从/ dev/input/event4读取条形码.这是代码:
#include <sys/file.h>
#include <stdio.h>
#include <string.h>
#include <linux/input.h>
int main (int argc, char *argv[])
{
struct input_event ev;
int fd, rd;
//Open Device
if ((fd = open ("/dev/input/event4", O_RDONLY|O_NONBLOCK)) == -1){
printf ("not a vaild device.\n");
return -1;
}
while (1){
memset((void*)&ev, 0, sizeof(ev));
rd = read (fd, (void*)&ev, sizeof(ev));
if (rd <= 0){
printf ("rd: %d\n", rd);
sleep(1);
}
if(rd>0 && ev.value==0 && ev.type==1){
printf("type: %d, code: %d, value: %d, rd: %d\n", ev.type, ev.code, ev.value, rd);
} …Run Code Online (Sandbox Code Playgroud)