I want to record and play keyboard events on my Linux machine.
Basically i store all the keyboard events entered by the user into a text file. For this, i am simply reading the device file: /dev/input/event0 using read() and storing the events into a text file. While playback i read() the text file and write() the events to the device file.
The code also stores and plays the time difference between the keys pressed.
The code works fine for mouse, but for keyboard it is giving some problems. While playback it shows the proper output including the delay but once the program terminates it dumps the entire entered string on the terminal.
Here's an example usage:
Recording
# ./record /dev/input/event0 ./record.txt
Now whatever the user enters thru the keyboard is recorded until the user presses the ctrl+c key.
Playback
# ./play /dev/input/event0 ./record.txt
Suppose i have entered "monty" while recording, and i have given 2 seconds delay after entering "mo" and then i entered "nty", here's the output:
mo(2seconds delay)nty
After this immediately the prompt returns and dumps the entire string:
#montyc
This "c" is shown as i had pressed Ctrl+C for stopping the recording...
Now, anybody knows while the entire string is getting dumped to the screen when the program terminates, and is there any way to resolve this.
Here's my code:
Recording Code:
FILE *deviceConnection,*record_file;
struct input_event myEvent;
deviceConnection = fopen(argv[1], "rw");
record_file = fopen(argv[2], "rw+");
while (1) {
printf(".");
// read from the device file into the input_event structure */
fread(&myEvent, sizeof(struct input_event), 1, deviceConnection);
// Write the events to the text file */
fwrite(&myEvent, sizeof(struct input_event), 1, record_file);
fflush(record_file);
}
fclose(deviceConnection);
fclose(record_file); Playback Code:
FILE *record_file;
struct input_event myEvent;
char filename[128] ;
int devHandle = -1;
devHandle = open(argv[1], O_RDWR);
record_file = fopen(argv[2], "r+");
while (!feof(record_file))
{
fread(&myEvent, sizeof(struct input_event), 1, record_file);
if (myEvent.value != 0) {
printf ("We are in Key Press \n");
write(devHandle, &(myEvent), sizeof(struct input_event);
}
}
close (devHandle);
fclose(record_file);