在C++中使用std::ofstream创建具有随机文件名的文件时出现问题

Problems while creating files with random file names while using std::ofstream in C++

本文关键字:文件名 随机 文件 问题 C++ std 创建 ofstream      更新时间:2023-10-16

我有这段代码,我正在努力让它发挥作用(没有duh right)现在它创建了一个大文件,但我希望它生成一系列随机命名的文件。

#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
#include <fstream>  
using namespace std;
string random(int len)
{
    string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    string r;
    srand(time(NULL));
    for(int i = 0; i < len; i++) r.push_back(a.at(size_t(rand() % 62)));
    return r;
}
int main(){
    std::ofstream o("largefile.txt");
    o << random(999) << std::endl;
    return 0;
}

我试着添加这个,但我在std::ofstream 中得到了一个关于数据类型的错误

std::string file=random(1);
std::ofstream o(file);
std::string file=random(1);
std::ofstream o(file);

应该是:

std::string file=random(1);
std::ofstream o(file.c_str());

因为CCD_ 2的构造函数期望CCD_。


也可以考虑使用以下函数而不是rand() % 62

inline int irand(int min, int max) {
    return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}
...
srand(time(NULL));                    // <-- be careful not to call srand in loop
std::string r;
r.reserve(len);                       // <-- prevents exhaustive reallocation
for (int i = 0; i < len; i++)
    r.push_back( a[irand(0,62)] );