2012-11-06 39 views
-1

我有一段用符合POSIX标准的C语言编写的代码,它似乎不能正常工作。目标是从/ dev/random读取Linux/BSD/Darwin内核的随机数生成器的接口,并将写入的字节输出到文件中。我不太确定我忽略了什么,因为我确信我已经覆盖了每一个领域。无论如何,这里是:从/ dev/random读取字节失败

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

什么不起作用 - 有哪些错误? – Mark

+5

向这些'read()'/'write()'调用添加错误检查,并使用'strerror(errno)'报告错误。另外,你不读/写'字节',你正在读/写'int's。 – trojanfoe

+0

它只是静静地失败...操作系统报告的文件大小是相同的,当我打开文件没有被改变。我在一个文本文件上测试了这个,所以我能够检测到变化。 – SevenBits

回答

4

而不是

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

你一定的意思是写

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

不是吗?如果使用从/dev/random读取的随机字节作为指针,则几乎肯定会迟早地遇到segfault。

+0

谢谢大家!我应用了所有的建议,代码现在正在运行!太感谢了! – SevenBits