fileName.H
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration |
5  \\ / A nd | www.openfoam.com
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8  Copyright (C) 2011-2017 OpenFOAM Foundation
9  Copyright (C) 2016-2023 OpenCFD Ltd.
10 -------------------------------------------------------------------------------
11 License
12  This file is part of OpenFOAM.
13 
14  OpenFOAM is free software: you can redistribute it and/or modify it
15  under the terms of the GNU General Public License as published by
16  the Free Software Foundation, either version 3 of the License, or
17  (at your option) any later version.
18 
19  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
20  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22  for more details.
23 
24  You should have received a copy of the GNU General Public License
25  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
26 
27 Class
28  Foam::fileName
29 
30 Description
31  A class for handling file names.
32 
33  A fileName is a string of characters without whitespace or quotes.
34  A fileName can be
35  - constructed from a char*, a string or a word
36  - concatenated by adding a '/' separator
37  - decomposed into the path, name or component list
38  - interrogated for type and access mode
39 
40  The string::expand() method expands environment variables, etc,
41 
42 SourceFiles
43  fileName.C
44  fileNameI.H
45  fileNameIO.C
46 
47 \*---------------------------------------------------------------------------*/
48 
49 #ifndef Foam_fileName_H
50 #define Foam_fileName_H
51 
52 #include "word.H"
53 
54 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
55 
56 namespace Foam
57 {
58 
59 // Forward Declarations
60 class fileName;
61 class token;
62 
63 template<class T> class List;
64 template<class T> class UList;
66 
67 //- Hashing for fileName
68 template<> struct Hash<fileName> : string::hasher {};
69 
70 
71 /*---------------------------------------------------------------------------*\
72  Class fileName Declaration
73 \*---------------------------------------------------------------------------*/
74 
75 class fileName
76 :
77  public string
78 {
79 public:
80 
81  //- Enumerations to handle directory entry types.
82  enum Type
83  {
84  UNDEFINED = 0,
85  FILE = 1,
86  DIRECTORY = 2,
87  SYMLINK = 4,
88  LINK = SYMLINK
89  };
90 
91 
92  // Static Data Members
93 
94  //- The typeName
95  static const char* const typeName;
96 
97  //- Debugging
98  static int debug;
99 
100  //- Allow space character in fileName. To be used with caution.
102 
103  //- An empty fileName
104  static const fileName null;
105 
107  // Constructors
108 
109  //- Default construct
110  fileName() = default;
112  //- Copy construct
113  fileName(const fileName&) = default;
114 
115  //- Move construct
116  fileName(fileName&&) = default;
117 
118  //- Copy construct from word
119  inline fileName(const word& s);
120 
121  //- Move construct from word
122  inline fileName(word&& s);
123 
124  //- Copy construct from string
125  inline fileName(const string& s, bool doStrip=true);
126 
127  //- Move construct from string
128  inline fileName(string&& s, bool doStrip=true);
129 
130  //- Copy construct from std::string
131  inline fileName(const std::string& s, bool doStrip=true);
132 
133  //- Move construct from std::string
134  inline fileName(std::string&& s, bool doStrip=true);
135 
136  //- Copy construct from character array
137  inline fileName(const char* s, bool doStrip=true);
138 
139  //- Construct by concatenating elements of wordList separated by '/'
140  explicit fileName(const UList<word>& list);
141 
142  //- Construct by concatenating words separated by '/'
143  explicit fileName(std::initializer_list<word> list);
144 
145  //- Construct from Istream
146  explicit fileName(Istream& is);
147 
148 
149  // Member Functions
150 
151  //- Inherit all regular string assign() methods
152  using string::assign;
153 
154  //- Assign from word or string token.
155  // \return false if the token was the incorrect type
156  bool assign(const token& tok);
157 
158  //- Is this character valid for a fileName?
159  inline static bool valid(char c);
160 
161  //- Construct fileName without invalid characters, possibly applying
162  //- other transformations such as changing the path separator,
163  //- removing duplicate or trailing slashes, etc.
164  static fileName validate(const std::string&, const bool doClean=true);
165 
166  //- Join two strings with a path separator ('/' by default).
167  // No separator is added if either argument is an empty string or
168  // if the arguments already had the path separator at the junction.
169  // Invalid characters are \em not stripped (ie, retained).
170  static fileName concat
171  (
172  const std::string& s1,
173  const std::string& s2,
174  const char delim = '/'
175  );
176 
177  //- This is a specialized (possibly slower) version of compare()
178  //- that ignores duplicate or trailing slashes.
179  static bool equals(const std::string& s1, const std::string& s2);
180 
181  //- Strip invalid characters
182  inline void stripInvalid();
183 
184  //- Cleanup filename string, possibly applies other transformations
185  //- such as changing the path separator etc.
186  //
187  // Changes back-slash to forward-slash path separator,
188  // while preserving windows UNC:
189  // \verbatim
190  // \\server\abc\def --> \\server/abc/def
191  // \endverbatim
192  //
193  // Removes trailing slash:
194  // \verbatim
195  // / --> /
196  // /abc/ --> /abc
197  // \endverbatim
198  //
199  // Removes repeated slashes, but preserves UNC:
200  // \verbatim
201  // /abc////def --> /abc/def
202  // \\server\abc////def --> \\server/abc/def
203  // \endverbatim
204  //
205  // Removes \c "/./" (current directory), except for leading one:
206  // \verbatim
207  // /abc/def/./ghi/. --> /abc/def/ghi
208  // abc/def/./ --> abc/def
209  // ./abc/ --> ./abc
210  // \endverbatim
211  //
212  // Removes \c "/../" (parent directory), except for leading one:
213  // \verbatim
214  // /abc/def/../ghi/jkl/nmo/.. --> /abc/ghi/jkl
215  // abc/../def/ghi/../jkl --> abc/../def/jkl
216  // \endverbatim
217  // .
218  //
219  // \return True if the content changed
220  static bool clean(std::string& str);
221 
222  //- Cleanup filename (inplace)
223  // \return True if the content changed
224  bool clean();
225 
226 
227  // Interrogation
228 
229  //- Return the directory entry type:
230  //- UNDEFINED, FILE, DIRECTORY (or SYMLINK).
231  //
232  // \param followLink when false it will return SYMLINK for a symlink
233  // rather than following it.
234  // \param checkGzip add an additional test for a gzip FILE
235  Type type(bool followLink=true, bool checkGzip=false) const;
236 
237  //- Return true if filename starts with a '/' or '\\'
238  //- or (windows-only) with a filesystem-root
239  inline static bool isAbsolute(const std::string& str);
240 
241  //- Return true if filename is absolute,
242  //- which means it starts with a '/' or '\\'
243  //- or (windows-only) with a filesystem-root
244  inline bool isAbsolute() const;
245 
246  //- Convert from relative to absolute.
247  // As a side-effect, always performs a clean() to remove "/./" etc
248  fileName& toAbsolute();
249 
250  //- Return true if string ends with "~", ".bak", ".old", ".save"
251  static bool isBackup(const std::string& str);
252 
253  //- Return true if file name ends with "~", ".bak", ".old", ".save"
254  inline bool isBackup() const;
255 
256 
257  // Decomposition
258 
259  //- Return directory path name (part before last /)
260  // The result normally corresponds to a Foam::fileName
261  //
262  // Behaviour compared to /usr/bin/dirname:
263  // \verbatim
264  // input path() dirname
265  // ----- ------ -------
266  // "" "." "."
267  // "abc" "." "."
268  // "/" "/" "/"
269  // "/abc" "/" "/"
270  // "abc/def" "abc" "abc"
271  // "/abc/def" "/abc" "/abc"
272  // "/abc/def/" "/abc/def" "/abc"
273  // "/abc/../def" "/abc/.." "/abc/.."
274  // \endverbatim
275  inline static std::string path(const std::string& str);
276 
277  //- Return directory path name (part before last /)
278  inline fileName path() const;
279 
280  //- Remove leading path, return true if string changed.
281  using string::remove_path;
282 
283  //- True if it contains a '/' character
284  inline bool has_path() const;
285 
286 
287  //- Return basename (part beyond last /), including its extension
288  // The result normally corresponds to a Foam::word
289  //
290  // Behaviour compared to /usr/bin/basename:
291  // \verbatim
292  // input name() basename
293  // ----- ------ --------
294  // "" "" ""
295  // "abc" "abc" "abc"
296  // "/" "" "/"
297  // "/abc" "abc" "abc"
298  // "abc/def" "def" "def"
299  // "/abc/def" "def" "def"
300  // "/abc/def/" "" "def"
301  // "/abc/../def" "def" "def"
302  // \endverbatim
303  inline static std::string name(const std::string& str);
304 
305  //- Return basename (part beyond last /), including its extension
306  inline word name() const;
307 
308  //- Replace basename (part beyond last /) with a new name
309  fileName& replace_name(const word& newName);
310 
311  //- Return the basename, without extension
312  // The result normally corresponds to a Foam::word
313  static std::string stem(const std::string& str);
314 
315  //- Return basename, without extension
316  inline word stem() const;
317 
318 
319  //- Return file name extension (part after last .)
320  inline word ext() const;
321 
322  //- Append a '.' and the ending, and return the object.
323  // The '.' and ending will not be added when the ending is empty,
324  // or when the file name is empty or ended with a '/'.
325  inline fileName& ext(const word& ending);
326 
327  //- Remove extension (if any) and append a new one
328  inline fileName& replace_ext(const word& ending);
329 
330  //- Return file name without extension (part before last .)
331  inline fileName lessExt() const;
332 
333  //- Remove extension, returning true if string changed.
334  using string::remove_ext;
335 
336  //- Various checks for extensions
337  using string::has_ext;
338 
339 
340  //- Return a relative name by stripping off the parent directory
341  //- where possible.
342  //
343  // \param parent the parent directory
344  // \param caseTag replace the parent with <case> for later
345  // use with expand(), or prefix <case> if the file name was
346  // not an absolute location
348  (
349  const fileName& parent,
350  const bool caseTag = false
351  ) const;
352 
353 
354  //- Return path components as wordList
355  //
356  // Behaviour:
357  // \verbatim
358  // input components()
359  // ----- ------------
360  // "" ()
361  // "." (".")
362  // "abc" ("abc")
363  // "/abc" ("abc")
364  // "abc/def" ("abc", "def")
365  // "/abc/def" ("abc", "def")
366  // "/abc/def/" ("abc", "def")
367  // \endverbatim
368  wordList components(const char delim = '/') const;
369 
370  //- Return a single component of the path or empty if out of range
371  // The location \c npos returns the last component
372  word component(const size_type cmpt, const char delim = '/') const;
373 
374 
375  // Member Operators
376 
377  // Assignment
378 
379  //- Copy assignment, no character validation required
380  // Self-assignment is a no-op.
381  inline fileName& operator=(const fileName& str);
382 
383  //- Move assignment, no character validation required
384  // Self-assignment is a no-op.
385  inline fileName& operator=(fileName&& str);
386 
387  //- Copy assignment, no character validation required
388  inline fileName& operator=(const word& str);
389 
390  //- Move assignment, no character validation required
391  inline fileName& operator=(word&& str);
392 
393  //- Copy assignment, stripping invalid characters
394  inline fileName& operator=(const string& str);
395 
396  //- Move assignment, stripping invalid characters
397  inline fileName& operator=(string&& str);
398 
399  //- Copy assignment, stripping invalid characters
400  inline fileName& operator=(const std::string& str);
401 
402  //- Move assignment, stripping invalid characters
403  inline fileName& operator=(std::string&& str);
404 
405  //- Copy, stripping invalid characters
406  inline fileName& operator=(const char* str);
407 
408 
409  // Other Operators
410 
411  //- Append a path element with '/' separator.
412  // No '/' separator is added if this or the argument are empty.
413  fileName& operator/=(const string& other);
414 
415 
416  // Housekeeping
417 
418  //- Same as has_path()
419  bool hasPath() const { return has_path(); }
420 
421  //- Same as remove_path()
422  bool removePath() { return remove_path(); }
423 
424  //- Same as has_ext()
425  bool hasExt() const { return has_ext(); }
426 
427  //- Same as has_ext()
428  bool hasExt(const std::string& s) const { return has_ext(s); }
429 
430  //- Same as remove_ext()
431  bool removeExt() { return remove_ext(); }
432 
433  //- Same as stem()
434  static std::string nameLessExt(const std::string& s)
435  {
436  return fileName::stem(s);
437  }
438 
439  //- Same as stem()
440  word nameLessExt() const { return stem(); }
441 
442  //- Deprecated(2017-03) return basename, optionally without extension
443  // \deprecated(2017-03) - use name() or stem() methods
444  // which describe their behaviour explicitly
445  word name(const bool noExt) const
446  {
447  return noExt ? stem() : name();
448  }
449 };
450 
451 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
452 
453 // IOstream Operators
454 
455 //- Read operator
456 Istream& operator>>(Istream& is, fileName& val);
457 
458 //- Write operator
459 Ostream& operator<<(Ostream& os, const fileName& val);
460 
461 
462 // Global Operators
463 
464 //- Assemble words and fileNames as pathnames by adding a '/' separator.
465 // No '/' separator is added if either argument is an empty string.
466 fileName operator/(const string& s1, const string& s2);
467 
468 
469 //- Recursively search the given directory for the file
470 // returning the path relative to the directory or
471 // fileName::null if not found
472 fileName search(const word& file, const fileName& directory);
473 
474 
475 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
476 
477 } // End namespace Foam
478 
479 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
480 
481 #include "fileNameI.H"
482 
483 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
484 
485 #endif
486 
487 // ************************************************************************* //
A symbolic link.
Definition: fileName.H:86
static int debug
Debugging.
Definition: fileName.H:101
A class for handling file names.
Definition: fileName.H:72
fileName & operator/=(const string &other)
Append a path element with &#39;/&#39; separator.
Definition: fileName.C:577
bool clean()
Cleanup filename (inplace)
Definition: fileName.C:385
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bound...
Definition: BitOps.H:56
word nameLessExt() const
Same as stem()
Definition: fileName.H:589
word stem() const
Return basename, without extension.
Definition: fileNameI.H:217
An Istream is an abstract base class for all input systems (streams, files, token lists etc)...
Definition: Istream.H:57
A token holds an item read from Istream.
Definition: token.H:65
static const fileName null
An empty fileName.
Definition: fileName.H:111
Undefined type.
Definition: fileName.H:83
Type type(bool followLink=true, bool checkGzip=false) const
Return the directory entry type: UNDEFINED, FILE, DIRECTORY (or SYMLINK).
Definition: fileName.C:353
dimensionedScalar operator/(const scalar s1, const dimensionedScalar &ds2)
static const char *const typeName
The typeName.
Definition: fileName.H:96
static bool equals(const std::string &s1, const std::string &s2)
This is a specialized (possibly slower) version of compare() that ignores duplicate or trailing slash...
Definition: fileName.C:238
fileName & replace_ext(const word &ending)
Remove extension (if any) and append a new one.
Definition: fileNameI.H:230
word ext() const
Return file name extension (part after last .)
Definition: fileNameI.H:211
word component(const size_type cmpt, const char delim='/') const
Return a single component of the path or empty if out of range.
Definition: fileName.C:552
bool has_path() const
True if it contains a &#39;/&#39; character.
Definition: fileNameI.H:163
bool assign(const token &tok)
Assign from word or string token.
Definition: fileNameIO.C:35
bool has_ext() const
Return true if it has an extension or simply ends with a &#39;.&#39;.
Definition: stringI.H:43
fileName relative(const fileName &parent, const bool caseTag=false) const
Return a relative name by stripping off the parent directory where possible.
Definition: fileName.C:443
fileName()=default
Default construct.
void stripInvalid()
Strip invalid characters.
Definition: fileNameI.H:106
bool isAbsolute() const
Return true if filename is absolute, which means it starts with a &#39;/&#39; or &#39;\&#39; or (windows-only) with a...
Definition: fileNameI.H:151
A class for handling words, derived from Foam::string.
Definition: word.H:63
Istream & operator>>(Istream &, directionInfo &)
A regular file.
Definition: fileName.H:84
word name() const
Return basename (part beyond last /), including its extension.
Definition: fileNameI.H:205
bool removePath()
Same as remove_path()
Definition: fileName.H:561
Same as symlink.
Definition: fileName.H:87
graph_traits< Graph >::vertices_size_type size_type
Definition: SloanRenumber.C:68
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
Definition: HashTable.H:105
void assign(Field< Tout > &result, const Field< T1 > &a, const UnaryOp &op)
Populate a field as the result of a unary operation on an input.
Definition: FieldOps.C:28
fileName & toAbsolute()
Convert from relative to absolute.
Definition: fileName.C:370
wordList components(const char delim='/') const
Return path components as wordList.
Definition: fileName.C:532
bool hasPath() const
Same as has_path()
Definition: fileName.H:556
OBJstream os(runTime.globalPath()/outputName)
static bool valid(char c)
Is this character valid for a fileName?
Definition: fileNameI.H:95
static fileName concat(const std::string &s1, const std::string &s2, const char delim='/')
Join two strings with a path separator (&#39;/&#39; by default).
Definition: fileName.C:211
Hashing functor for string and derived string classes.
Definition: string.H:171
fileName & replace_name(const word &newName)
Replace basename (part beyond last /) with a new name.
Definition: fileName.C:419
Ostream & operator<<(Ostream &, const boundaryPatch &p)
Write boundaryPatch as dictionary entries (without surrounding braces)
Definition: boundaryPatch.C:77
List< word > wordList
List of word.
Definition: fileName.H:59
bool removeExt()
Same as remove_ext()
Definition: fileName.H:576
bool remove_path()
Remove leading path, return true if string changed.
Definition: stringI.H:79
Hash function class. The default definition is for primitives. Non-primitives used to hash entries on...
Definition: Hash.H:47
static int allowSpaceInFileName
Allow space character in fileName. To be used with caution.
Definition: fileName.H:106
bool isBackup() const
Return true if file name ends with "~", ".bak", ".old", ".save".
Definition: fileNameI.H:157
static fileName validate(const std::string &, const bool doClean=true)
Construct fileName without invalid characters, possibly applying other transformations such as changi...
Definition: fileName.C:199
const dimensionedScalar c
Speed of light in a vacuum.
fileName lessExt() const
Return file name without extension (part before last .)
Definition: fileNameI.H:238
bool hasExt() const
Same as has_ext()
Definition: fileName.H:566
fileName path() const
Return directory path name (part before last /)
Definition: fileNameI.H:186
fileName search(const word &file, const fileName &directory)
Recursively search the given directory for the file.
Definition: fileName.C:642
gmvFile<< "tracers "<< particles.size()<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().x()<< " ";}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().y()<< " ";}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().z()<< " ";}gmvFile<< nl;forAll(lagrangianScalarNames, i){ word name=lagrangianScalarNames[i];IOField< scalar > s(IOobject(name, runTime.timeName(), cloud::prefix, mesh, IOobject::MUST_READ, IOobject::NO_WRITE))
A class for handling character strings derived from std::string.
Definition: string.H:72
Type
Enumerations to handle directory entry types.
Definition: fileName.H:81
Namespace for OpenFOAM.
fileName & operator=(const fileName &str)
Copy assignment, no character validation required.
Definition: fileNameI.H:253
bool remove_ext()
Remove extension, return true if string changed.
Definition: stringI.H:93