I have an USB RFID card reader which emulates keyboard.
So when i put an card to it i see the string on a terminal window -i.e. "0684a24bc1"
But i would like to read it in my C program.
There is no problem when i use: scanf("%s",buff);
But when i use below code i got a lot (about 500 bytes) not recognized data.
Why?
I would like to have non blocking read.
#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) {
perror("Read failed - ");
return -1;
} else if (n == 0) printf("No data on port
");
else {
buf[n] = '';
printf("%i bytes read : %s", n, buf);
}
sleep(1);
printf("i'm still doing something");
}
close(fd);
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…