#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

const char file_name[] = "/dev/random";

enum { num_chars = 9 };

long str2long(const char *str)
{
    int n;
    char *endptr;

    n = strtol(str, &endptr, 10);
    if (errno == ERANGE)
        n = -1;
    if (!*str || *endptr)
        n = -1;

    return n;
}

int main()
{
    int fd, random, rc;
    char buf[num_chars];

    fd = open(file_name, O_RDONLY);
    if (fd == -1) {
        perror(file_name);
        return 1;
    }
    rc = read(fd, buf, num_chars);
    if (rc <= 0) {
        perror(file_name);
        return 1;
    }
    buf[rc] = 0;

    printf("%s\n", buf);
    random = str2long(buf);
    printf("%d\n", random);

    close(fd);
    return 0;
}
