Code:
#include <linux/input.h>
#include <sys/ioctl.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int list_input_devices();
int* read_numbers(FILE* fd, int num);
int main()
{
int numdev, i;
int* numbers;
const int numbers_to_read = 10;
char temp[100];
char output1[100], output2[100];
int max, min;
FILE* fd;
numdev = list_input_devices();
if(numdev == 0)
{
printf("Error. Couldn't find any usable input devices.\n");
return -1;
}
do
{
printf("Enter the number of your keyboard device: ");
fgets(temp, sizeof(temp), stdin);
} while(sscanf(temp, "%d", &numdev) != 1);
snprintf(temp, sizeof(temp), "/dev/input/event%d", numdev);
fd = fopen(temp, "rb");
if(fd == 0)
{
printf("Error. Couldn't open input device.\n");
return -2;
}
numbers = read_numbers(fd, 10);
fclose(fd);
if(numbers == NULL)
{
printf("Error. Couldn't read from input device.\n");
return -3;
}
min = max = sizeof(numbers[0]);
printf("\nNumbers:\n");
for(i=0; i<numbers_to_read; i++)
{
if(min > sizeof(numbers[i]))
min = sizeof(numbers[i]);
if(max < sizeof(numbers[i]))
max = sizeof(numbers[i]);
printf(" %d\n", numbers[i]);
}
sprintf(output1, "Index(es) of smallest element(s): ");
sprintf(output2, "Index(es) of largest element(s): ");
for(i=0; i<numbers_to_read; i++)
{
sprintf(temp, "%d ", i);
if(sizeof(numbers[i] == min))
strcat(output1, temp);
if(sizeof(numbers[i] == max))
strcat(output2, temp);
}
free(numbers);
strcat(output1, "\n");
strcat(output2, "\n");
printf("Smallest element is %d bytes\n", min);
printf("Largest element is %d bytes\n", max);
printf(output1);
printf(output2);
return 0;
}
int list_input_devices()
{
int fd, count = 0;
struct dirent* dp;
char name[100];
char dev[100];
char devnum[10];
DIR* dir;
dir = opendir("/dev/input");
if(!dir)
return 0;
while((dp = readdir(dir)) != NULL)
{
if(dp->d_name && !strncmp(dp->d_name, "event", 5))
{
snprintf(dev, sizeof(dev), "/dev/input/%s", dp->d_name);
fd = open(dev, O_RDONLY);
if(fd == -1)
{
continue;
}
if(ioctl(fd, EVIOCGNAME(sizeof(name)), name) < 0)
{
close(fd);
continue;
}
else
{
snprintf(devnum, sizeof(devnum), "%s", dp->d_name+5);
printf("%s : %s\n", devnum, name);
close(fd);
count++;
}
}
}
closedir(dir);
return count;
}
int* read_numbers(FILE* fd, int num)
{
int* ret;
if(num < 1)
return NULL;
ret = malloc(sizeof(int) * num);
if(fread(ret, sizeof(int), num, fd) != num)
{
free(ret);
return NULL;
}
return ret;
}