Random filename
Hi all. Im trying to make a ofstream function that creates a file with a random number behind the file
First i tried this:
#include <ctime>
#include <fstream>
using namespace std;
int main()
{
char file[1024];
srand((unsigned)time(0));
int randomnumber;
randomnumber=rand();
sprintf(file,"%s_.txt",randomnumber);
ofstream out;
out.open(file, ios::app);
out << "test " << endl;
out.close();
return 0;
}
But the program crashes. What am i doing wrong? Thanx in advance!
# 1 Re: Random filename
Try this:
Create temporary filenames.
char *_tempnam( char *dir, char *prefix );
wchar_t *_wtempnam( wchar_t *dir, wchar_t *prefix );
char *tmpnam( char *string );
wchar_t *_wtmpnam( wchar_t *string );
# 2 Re: Random filename
printf() style functions are not typesafe
sprintf(file,"%d_.txt",randomnumber); // not %s
Here is a typesafe method:
#include <ctime>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
template <typename T1 , typename T2>
T2 Convert(const T1 & t1)
{
std::stringstream ss;
ss << t1;
T2 t2 = T2();
ss >> t2;
return t2;
}
int main()
{
srand((unsigned)time(0));
string file = Convert<int,string>(rand()) + "_.txt";
ofstream out;
out.open(file.c_str(), ios::app);
out << "test " << endl;
return 0;
}
# 3 Re: Random filename
In your original code, you have: sprintf(file,"%s_.txt",randomnumber);
The problem here is you use %s as the format, but the argument is an int.
Use sprintf(file,"%d_.txt",randomnumber);
instead.
Hope that helps.
krmed at 2007-11-11 4:04:27 >
