Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
FileHandling.hh
1 /*
2 This file is part of the BIAS library (Basic ImageAlgorithmS).
3 
4 Copyright (C) 2003-2009 (see file CONTACT for details)
5  Multimediale Systeme der Informationsverarbeitung
6  Institut fuer Informatik
7  Christian-Albrechts-Universitaet Kiel
8 
9 
10 BIAS is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 2.1 of the License, or
13 (at your option) any later version.
14 
15 BIAS is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU Lesser General Public License for more details.
19 
20 You should have received a copy of the GNU Lesser General Public License
21 along with BIAS; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 */
24 #ifndef __FileHandling_hh__
25 #define __FileHandling_hh__
26 
27 #include <bias_config.h>
28 
29 #include <string>
30 #include <sstream>
31 #include <vector>
32 #include <iomanip>
33 #include <stdio.h>
34 
35 #define DEFAULT_LEADING_ZEROS 5
36 
37 
38 namespace BIAS {
39 
40 /**
41  * @class FileHandling
42  * @brief Functions to create, check and delete files and to handle file
43  * names, such as splitting into directory, filename and suffix.
44  * @author BIAS
45  * @todo Correct handling of Win32 SAMBA paths including \\machine\...
46  */
47 class BIASCommon_EXPORT FileHandling
48 {
49 public:
50 
51  /** @brief Delete directory and all contents. */
52  static int RemoveDir(const std::string &subdir);
53 
54  /** @brief Create directory (parent directory must exist). */
55  static int CreateDir(const std::string &subdir);
56 
57  /** @brief Create directory recursively (if any parent directory does not
58  exist it will be created). */
59  static int CreateDirRecursive(const std::string &dir);
60 
61  /** @brief Check if the given file exists. */
62  static bool FileExists(const std::string &file);
63 
64  /**
65  @brief Read all files in @param Dir, match against @param suffix and
66  @param prefix and put into @param content. If you want to use the full
67  path, set @param GetFullPath=true, otherwise only the file name is used.
68  */
69  static int GetDirectoryContent(const std::string &Dir,
70  const std::string &prefix,
71  const std::string &suffix,
72  std::vector<std::string> &content,
73  const bool GetFullPath = false);
74 
75  /** @brief Checks if the given file exists and is readable on file system. */
76  static bool FileReadable(const std::string &filename);
77 
78  /** @brief Removes the file with the given name. Just wraps C call. */
79  static inline
80  bool RemoveFile(const std::string &filename)
81  {
82  return (remove(filename.c_str()) == 0);
83  }
84 
85  /** @brief Renames or moves the file with the given name. Just wraps C call. */
86  static inline
87  bool MoveOrRenameFile(const std::string &oldFilename, const std::string &newFilename)
88  {
89  return (rename(oldFilename.c_str(), newFilename.c_str()) == 0);
90  }
91 
92  /** @brief Copies the file with the given name. */
93  static
94  bool CopyFileTo(const std::string &oldFilename, const std::string &newFilename);
95 
96  /** @brief Converts number to string with leading zeros. */
97  template <class T>
98  inline static std::string toString(const T thenumber,
99  int numzeros = DEFAULT_LEADING_ZEROS)
100  {
101  std::stringstream ss;
102  ss << std::setfill('0')<<std::setw(numzeros)<<thenumber;
103  return ss.str();
104  }
105 
106  /** @brief Split full path into:
107  - directory
108  - file base name
109  - file suffix (including dot!)
110  @todo Extract machine name or IP for SMB network shares for WIN32, e.g.
111  \\machine\share, and fix backslashes on WIN32.
112  Fix also to make \, \\ and / work on directories!
113  @author Jan Woetzel
114  */
115  static void SplitName(const std::string &fullname, std::string &dir,
116  std::string &base, std::string &suffix);
117 
118  /** @brief Get directory from given path and filename. */
119  static std::string Directory(const std::string &fullname);
120 
121  /** @brief Get file base name without path from given path and filename. */
122  static std::string Basename(const std::string &fullname);
123 
124  /** @brief Get file suffix (including dot!) from given path and filename. */
125  static std::string Suffix(const std::string &fullname);
126 
127  /** @brief Get file extension (without dot!) from given path and filename. */
128  static std::string Extension(const std::string &fullname);
129 
130  /** @brief Get file name (base name + suffix) without path from given path
131  and filename. */
132  static std::string Filename(const std::string &fullname);
133 
134  /** @brief Get path and file base name (without suffix) from given path
135  and filename. */
136  static std::string DirectoryAndBasename(const std::string &fullname);
137 
138  /** @brief Split full directory name into individual subdirectory names,
139  e.g. /home/user/data -> ["home", "user", "data"].
140  @attention If a file name is given in @param fullpath, it will be
141  returned as the last element of @param result! */
142  static void SplitPath(const std::string &fullpath,
143  std::vector<std::string> &result);
144 
145  /** @brief Return lower case string of input. */
146  static std::string LowerCase(const std::string &input);
147 
148  /** @brief Return upper case string of input. */
149  static std::string UpperCase(const std::string &input);
150 
151  /** @brief Write compilation time/date and all command line arguments
152  to an output stream. */
153  static void LogCommandLine( int argc, char** argv, std::ostream &os);
154 
155  /** @brief Write compilation time/date and all command line arguments
156  to a log file. */
157  static void LogCommandLine(int argc, char** argv, const std::string & filename);
158 
159  /** @brief Create a string with leading zeroes from number
160  @deprecated Use FileHandling::toString(n, digits) instead! */
161  static std::string LeadingZeroString(const int &n,
162  const unsigned int &digits=DEFAULT_LEADING_ZEROS);
163 
164  /** @brief Create a string containing date and time like 20060329_173054
165  @author koeser */
166  static std::string CurrentDateTimeString();
167 
168  /** @brief Extract numeric value from string beginning from right, e.g.
169  "blah042foo.txt" --> return 42 and positions of "0" and "2". */
170  static int ExtractNumberFromRight(const std::string &inStr,
171  int &number, int &posL, int &posR );
172 
173  /** @brief Construct sequential filename from a given filename by manipulating
174  the number within base part of @param refFilename of an image
175  sequence given a reference filename and an offset. The number of
176  leading zeroes is kept but digits may be added if required.
177  @param offsetFromRef Number of frames forward or backward from ref. image
178  @param stepsize Number of increment/decrement per offset
179 
180  Example:
181  C:/foo/image00100bar.jpg
182  ref=100, offset=2, stepsize=7 --> 114
183  resultFilename --> C:/foo/image00114bar.jpg
184  or:
185  foo9 -> foo10
186  foo009 -> foo010
187 
188  @return 0 for success, !=0 for failure.
189  @author Jan Woetzel
190  */
191  static int FilenameSequence(const std::string &refFileName,
192  std::string &resultFilename,
193  const int &offsetFromRef,
194  const unsigned int &stepsize = 1);
195 
196  /** @brief Expand filename, e.g. tilde to home expands "~" to $HOME if set
197  and $USERPROFILE otherwise.
198  @author Jan Woetzel */
199  static int FilenameExpansion(const std::string &in, std::string &out);
200 
201  /** @brief Return current working directory as string. */
202  static std::string GetCwd();
203 
204  /** @brief Change current working directory. */
205  static int ChDir(const std::string &dir);
206 
207  /** @brief Return full path of current thread/application/module/exe/dll.
208  @author Jan Woetzel */
209  static std::string GetApplicationPath();
210 
211  /** @brief Determines if path is absolute (starting with "/") or local. */
212  static bool IsAbsolute(const std::string &path);
213 
214  /** @brief Remove a trailing slash from the path if there is one. */
215  inline static std::string StripTerminatingSlash(const std::string& thepath)
216  {
217  if (thepath.empty()) return thepath;
218  // separator for directory
219 #ifdef WIN32
220  std::string::size_type poslastslash = thepath.rfind('\\');
221 #else
222  std::string::size_type poslastslash = thepath.rfind('/');
223 #endif
224  if (poslastslash == thepath.size()-1) {
225  // copy everything without the trailing slash
226  return thepath.substr(0, poslastslash);
227  }
228  // already fine, no slash at the end of path
229  return thepath;
230  }
231 
232  /** @brief Replace wrong slashes with respect to current operating system. */
233  inline static std::string CorrectSlashes(const std::string& thepath)
234  {
235  // replace slash by backslash (Windows) or vice versa (Unix)
236  std::string result = thepath;
237 #ifdef WIN32
238  const std::string delimiter = "\\";
239  const std::string toReplace = "/";
240 #else
241  const std::string delimiter = "/";
242  const std::string toReplace = "\\";
243 #endif
244  std::string::size_type pos = result.find_first_of(toReplace);
245  while (pos != std::string::npos) {
246  result.replace(pos, 1, delimiter);
247  pos = result.find_first_of(toReplace, pos+1);
248  }
249  return result;
250  }
251 
252 private:
253 
254  /** @brief Type correct helper wrapper for tolower, required for chars. */
255  static char ToLower_c(char c);
256 
257  /** @brief Type correct helper wrapper for toupper, required for chars. */
258  static char ToUpper_c(char c);
259 
260 }; // class
261 
262 } // namespace BIAS
263 
264 #endif // __FileHandling_hh__
static bool MoveOrRenameFile(const std::string &oldFilename, const std::string &newFilename)
Renames or moves the file with the given name.
Definition: FileHandling.hh:87
static std::string toString(const T thenumber, int numzeros=DEFAULT_LEADING_ZEROS)
Converts number to string with leading zeros.
Definition: FileHandling.hh:98
static std::string CorrectSlashes(const std::string &thepath)
Replace wrong slashes with respect to current operating system.
static bool RemoveFile(const std::string &filename)
Removes the file with the given name.
Definition: FileHandling.hh:80
Functions to create, check and delete files and to handle file names, such as splitting into director...
Definition: FileHandling.hh:47
static std::string StripTerminatingSlash(const std::string &thepath)
Remove a trailing slash from the path if there is one.