C++ STL 快速生成带后缀的随机文件名

如果你不想使用系统API或者API不可用,那么可使用以下类似代码代替随机文件名的生成,代码生成4到32位长度的随机文件名,并以.txt结尾。
#include <string>
#include <random>
static std::string random_name()
{
	const char cs[] = "0a{1b2c3d$4e5f6g7h_8@i9jAkBl`CmDnEo[FpGqHrI~s-JtKuLvMw%NxOyPz(Q9R8S7T6)U5V4]W3X2}Y1Z0";
	std::random_device r;
	std::default_random_engine e(r());
	std::uniform_int_distribution<> u(0, _countof(cs) - 2);

	char n[((_countof(cs) - 2) + 12) / 3 + _countof(".txt")];
	int l = (u(e) + 12) / 3; // length [4, 32]
	strcpy(&n[l], ".txt");
	while (--l >= 0) {
		n[l] = cs[u(e)];
	}
	return n;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章