Question

I have this code I am trying to make work (no duh right) Right now it creates a single large file, but I want it to generate a series of randomly titled files.

#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;
}

I tried to add this, but I get an error about data types in std::ofstream

std::string file=random(1);
std::ofstream o(file);
Was it helpful?

Solution

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

should be:

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

since ofstream's constructor expects const char*.


Also consider using the following function instead of 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)] );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top