#include <iostream>
#include <string>
using namespace std;
#include <time.h>
#ifdef WIN32
#include <direct.h>//_mkdir
#include <io.h> //_access
#else
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#endif
/*
Title: 返回随机文件名。
Description: 如果当前目录下没有“年月日路径”目录创建它,并返回“时分秒+随机数”文件名。
Author: kagula
Date: 2016-03-14
Environment:
VS2013 Update5
GCC 4.8.5
*/
string generateFileName(string pathPrefix, string filenameSuffix)
{
string filname = pathPrefix;
if (filname.empty())
{
filname = ".";
}
time_t now_time;
now_time = time(NULL);
struct tm *localTime;
localTime = localtime(&now_time);
int year = 1900 + localTime->tm_year;
int month = 1 + localTime->tm_mon;
char bufDate[64];
char bufTime[64];
sprintf(bufDate, "%04d_%02d_%02d",
year, month, localTime->tm_mday);
//check directory if exist, if not exist create it
string dirname = pathPrefix;
if (dirname.empty())
{
dirname = ".";
}
dirname.append("/");
dirname.append(bufDate);
#ifdef WIN32
if ((_access(dirname.c_str(), 0)) != 0)
{
if (_mkdir(dirname.c_str()) != 0)
{
return "";
}
}
#else
if ((access(dirname.c_str(), R_OK)) != 0)
{
if (mkdir(dirname.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH) < 0)
{
return "";
}
}
#endif
//
int nR = (rand() % 10000) * 10000 + rand() % 10000;
sprintf(bufTime, "%02d%02d%02d_%08d.%s",
localTime->tm_hour, localTime->tm_min, localTime->tm_sec,
nR, filenameSuffix.c_str());
filname.append("/");
filname.append(bufDate);
filname.append("/");
filname.append(bufTime);
return filname;
}
int main(int argc, char* argv[])
{
cout << "test file name generate" << endl;
//
srand(unsigned(time(0)));
//
for (int i = 0; i < 100; i++)
{
cout << "[" << i << "] " << generateFileName("", "jpg") << endl;
}
cin.get();
return 0;
}