从/ dev / random读取字节失败

时间:2012-11-06 21:26:36

标签: c macos posix stdio

我有一段用符合POSIX标准的C编写的代码,它似乎无法正常工作。目标是从/ dev / random读取Linux / BSD / Darwin内核的随机数生成器的接口,并将写入的字节输出到文件。我不太清楚我在忽视什么,因为我确信我已经覆盖了所有的基础。无论如何,这是:

int incinerate(int number, const char * names[]) {
if (number == 0) {
    // this shouldn't happen, but if it does, print an error message
    fprintf(stderr, "Incinerator: no input files\n");
    return 1;
}

// declare some stuff we'll be using
long long lengthOfFile = 0, bytesRead = 0;
int myRandomInteger;

// open the random file block device
int zeroPoint = open("/dev/random", O_RDONLY);

// start looping through and nuking files
for (int i = 1; i < number; i++) {
    int filePoint = open(names[i], O_WRONLY);

    // get the file size
    struct stat st;
    stat(names[i], &st);
    lengthOfFile = st.st_size;
    printf("The size of the file is %llu bytes.\n", lengthOfFile);

    while (lengthOfFile != bytesRead) {
        read(zeroPoint, &myRandomInteger, sizeof myRandomInteger);
        write(filePoint, (const void*) myRandomInteger, sizeof(myRandomInteger));
        bytesRead++;
    }

    close(filePoint);
}

return 0;
}

有什么想法吗?这是在OS X上开发的,但我认为它没有理由不适用于Linux或FreeBSD。

如果有帮助,我已经包含以下标题:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

1 个答案:

答案 0 :(得分:4)

而不是

write(filePoint, (const void*) myRandomInteger, sizeof(myRandomInteger));

你肯定打算写

write(filePoint, (const void*) &myRandomInteger, sizeof(myRandomInteger));
不是吗?如果你使用从/dev/random读取的随机字节作为指针,你几乎肯定迟早会遇到段错误。