New program - better error reporting:#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main()
{
char data[16];
ssize_t n;
int fd;
errno = 0;
fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0) {
printf("open O_RDONLY succeeded\n");
n = read(fd, data, sizeof(data));
printf("read(%zd) -> %zi\n", sizeof(data), n);
close(fd);
}
else {
printf("open O_RDONLY failed with errno:%d:%s\n", errno, strerror(errno));
}
errno = 0;
fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
printf("open O_RDONLY | O_CLOEXEC succeeded\n");
n = read(fd, data, sizeof(data));
printf("read(%zd) -> %zi\n", sizeof(data), n);
close(fd);
}
else {
printf("open O_RDONLY | O_CLOEXEC failed with errno:%d:%s\n", errno, strerror(errno));
}
}
New program (use fopen())#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
char data[16];
ssize_t n;
FILE *f1;
f1 = fopen("/dev/urandom", "r");
if (f1 != NULL) {
printf("fopen \"r\" succeeded\n");
n = fread(data, sizeof(data), sizeof(char), f1);
printf("fread:requested (%zd) -> received(%zi)\n", sizeof(data), n);
fclose(f1);
}
else {
perror("fopen failed\n");
}
}