gpt4 book ai didi

c - 将/dev/urandom 读入C 字符串缓冲区

转载 作者:行者123 更新时间:2023-11-30 18:45:53 24 4
gpt4 key购买 nike

我正在尝试从 /dev/urandom 读取固定长度的内容到C中的字符串缓冲区中。但是,每次调用程序时读取的字节数都不同。下面是我的代码片段

char * buff = malloc(sizeof(char)*2048);
int fd = open("/dev/urandom", O_RDONLY);
read(fd, buff, 2048);
printf("%lu \n", strlen(buff)); // length varies but usually not 2048
printf("%s \n", buff);

发生此行为是因为字符串是 \0以 C 终止,所以假设有 \0前2048个字符中,第一个\0之后的内容会被截断吗?

感谢您的帮助。

最佳答案

不需要将其加载到字符串中,我认为这里您想要读取由 /dev/urandom 生成的随机 int,所以像这样的东西应该可以工作:

  int randomvalue;
FILE *fpointer;
fpointer = fopen("/dev/urandom", "rb");
fread(&randomvalue,sizeof(int),1,fpointer);
fclose(fpointer);

关于c - 将/dev/urandom 读入C 字符串缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com