如何生成一个好的随机种子传递给srand()? [英] How to generate a good random seed to pass to srand()?

查看:269
本文介绍了如何生成一个好的随机种子传递给srand()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C ++程序,该程序需要为其内部使用创建一个临时文件.我想通过运行多个进程来允许程序的并发执行,因此需要将临时文件名随机化,这样每个生成的进程都会生成一个唯一的临时文件名供自己使用.

I am writing a C++ program which needs to create a temporary file for its internal usage. I would like to allow concurrent executions of the program by running multiple processes, so the temporary file name needs to be randomized, that way each spawned process will generate a unique temporary file name for its own use.

我正在使用rand()为文件名的一部分生成随机字符,因此我需要使用srand()初始化随机数生成器的种子.

I am using rand() to generate random characters for part of the file name, so i need to initialize the random number generator's seed using srand().

有什么选项可以将良好的参数传递给srand(),以使两个进程不会使用相同的种子值进行初始化? 我的代码需要在Windows和Linux上都能工作.

What options are there for passing a good argument to srand() such that two processes will not be initialized with the same seed value? My code needs to work both on Windows and on Linux.

推荐答案

问题是 实际上 ,询问如何创建唯一命名的临时文件.

The question is actually asking how to create a uniquely-named temporary file.

操作系统可能为此提供了一个API,这意味着您不必生成自己的名称.

The operating system probably provides an API for this, which means you do not have to generate your own name.

在Windows上,其名为 GetTempFileName()GetTempPath() .

On Windows, its called GetTempFileName() and GetTempPath().

在Unix上,使用 tmpfile() .

On Unix, use tmpfile().

(Windows也支持tmpfile();但是,我听到其他人的报告说,尽管它在XP上能很好地工作,但是如果您在C:驱动器上并且不是管理员,则在Vista上会失败.最好将GetTempFileName()方法与自定义的安全路径一起使用)

(Windows supports tmpfile() too; however, I've heard reports that from others that, whilst it works nicely on XP, it fails on Vista if you're on the C: drive and you are not an administrator; best to use the GetTempFileName() method with a custom, safe path)

这篇关于如何生成一个好的随机种子传递给srand()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆