经常遇到要生成许多文件,而且需要保证每个文件的文件名不同的情况,于是产生了下面的通用代码。

 1 // 为了生成的文件名唯一
 2 #include <stdlib.h>
 3 #include <sstream>
 4 #include <iomanip>
 5 #include <time.h>
 6 #include <iostream>
 7 
 8 int64_t s_serialNumber = 0;
 9 
10 std::string GetTimePidString() {
11     struct ::tm tm_time;
12     time_t timestamp = time(0);
13     localtime_r(&timestamp, &tm_time);
14 
15     std::ostringstream oss;
16 
17     oss << std::setfill('0')
18             << 1900+tm_time.tm_year
19             << std::setw(2) << 1+tm_time.tm_mon
20             << std::setw(2) << tm_time.tm_mday
21             << '-' 
22             << std::setw(2) << tm_time.tm_hour
23             << std::setw(2) << tm_time.tm_min
24             << std::setw(2) << tm_time.tm_sec
25             << '.' 
26             << getpid();
27     return oss.str();
28 }
29 
30 int64_t GetSerialNumber() {
31     return __sync_add_and_fetch(&s_serialNumber, 1); 
32 }
33 
34 int main() {
35     for (int i = 0; i < 3; ++i) {
36         std::string str = GetTimePidString();
37         int64_t var = GetSerialNumber();
38         std::ostringstream os;
39         os << var << "_" << str << ".txt";
40         std::cout << os.str() << std::endl;
41     }
42 }
View Code

执行,结果为:

1_20160323-165005.13921.txt
2_20160323-165005.13921.txt
3_20160323-165005.13921.txt

 

posted on 2016-03-23 16:51  LyndonYoung  阅读(858)  评论(0编辑  收藏  举报