返回随机文件名

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kagula086

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值