Berkeley SfM
create_timestamped_filename.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2015 - Erik Nelson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  */
19 
20 #ifndef UTILS_STRINGS_CREATE_TIMESTAMPED_FILENAME_H
21 #define UTILS_STRINGS_CREATE_TIMESTAMPED_FILENAME_H
22 
23 #include <time.h>
24 #include <string>
25 
26 #include "join.h"
27 
28 namespace strings {
29 
30 // Creates a filename from base_name and extension that includes the current
31 // date and time. The date and time format is specified by format_string, with a
32 // default value of %Y%m%d_%H%M%s.
33 // e.g.
34 // base_name = filename
35 // extension = .ext
36 // format_string = %Y%m%d-%H%M%S
37 // output: filename_20150702_094750.ext
38 //
39 // If the system clock is not able to give us a time, default to
40 // basename.extension.
41 inline std::string CreateTimestampedFilename(const std::string &base_name,
42  const std::string &extension,
43  const char *format_string =
44  "%Y%m%d-%H%M%S") {
45  std::string output_filename, date_time_string;
46 
47  // Get the current date.
48  int size = 12;
49  char *date_time = static_cast<char *>(malloc(size));
50  date_time[0] = '\0';
51  time_t now = time(NULL);
52 
53  // If time exists, format date string.
54  if (now != -1) {
55  // Make sure there is enough room in the buffer to get the full date and
56  // time (specified by format_string). If there is not enough room, retry
57  // until there is.
58  int success = strftime(date_time, size - 1, format_string, gmtime(&now));
59  while (!success) {
60  free(date_time);
61  size += 10;
62  date_time = static_cast<char *>(malloc(size));
63  date_time[0] = '\0';
64  success = strftime(date_time, size - 1, format_string, gmtime(&now));
65  }
66  date_time_string = Join("_", std::string(date_time));
67  }
68  free(date_time);
69  return Join(base_name, date_time_string, ".", extension);
70 }
71 
72 } //\namespace strings
73 
74 #endif
std::string CreateTimestampedFilename(const std::string &base_name, const std::string &extension, const char *format_string="%Y%m%d-%H%M%S")
std::string Join(const std::vector< std::string > &tokens, const std::string &separator)
Definition: join.h:48