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-2022 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  fileNameIO.C
45 
46 \*---------------------------------------------------------------------------*/
47 
48 #ifndef Foam_fileName_H
49 #define Foam_fileName_H
50 
51 #include "word.H"
52 
53 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
54 
55 namespace Foam
56 {
57 
58 // Forward Declarations
59 class fileName;
60 class token;
61 
62 template<class T> class List;
63 template<class T> class UList;
65 
66 //- Hashing for fileName
67 template<> struct Hash<fileName> : string::hasher {};
68 
69 
70 /*---------------------------------------------------------------------------*\
71  Class fileName Declaration
72 \*---------------------------------------------------------------------------*/
73 
74 class fileName
75 :
76  public string
77 {
78 public:
79 
80  //- Enumerations to handle directory entry types.
81  enum Type
82  {
83  UNDEFINED = 0,
84  FILE = 1,
85  DIRECTORY = 2,
86  SYMLINK = 4,
87  LINK = SYMLINK
88  };
89 
90 
91  // Static Data Members
92 
93  //- The typeName
94  static const char* const typeName;
95 
96  //- Debugging
97  static int debug;
98 
99  //- Allow space character in fileName. To be used with caution.
101 
102  //- An empty fileName
103  static const fileName null;
104 
106  // Constructors
107 
108  //- Default construct
109  fileName() = default;
111  //- Copy construct
112  fileName(const fileName&) = default;
113 
114  //- Move construct
115  fileName(fileName&&) = default;
116 
117  //- Copy construct from word
118  inline fileName(const word& s);
119 
120  //- Move construct from word
121  inline fileName(word&& s);
122 
123  //- Copy construct from string
124  inline fileName(const string& s, bool doStrip=true);
125 
126  //- Move construct from string
127  inline fileName(string&& s, bool doStrip=true);
128 
129  //- Copy construct from std::string
130  inline fileName(const std::string& s, bool doStrip=true);
131 
132  //- Move construct from std::string
133  inline fileName(std::string&& s, bool doStrip=true);
134 
135  //- Copy construct from character array
136  inline fileName(const char* s, bool doStrip=true);
137 
138  //- Construct by concatenating elements of wordList separated by '/'
139  explicit fileName(const UList<word>& list);
140 
141  //- Construct by concatenating words separated by '/'
142  explicit fileName(std::initializer_list<word> list);
143 
144  //- Construct from Istream
145  explicit fileName(Istream& is);
146 
147 
148  // Member Functions
149 
150  //- Inherit all regular string assign() methods
151  using string::assign;
152 
153  //- Assign from word or string token.
154  // \return false if the token was the incorrect type
155  bool assign(const token& tok);
156 
157  //- Is this character valid for a fileName?
158  inline static bool valid(char c);
159 
160  //- Construct fileName without invalid characters, possibly applying
161  //- other transformations such as changing the path separator,
162  //- removing duplicate or trailing slashes, etc.
163  static fileName validate(const std::string&, const bool doClean=true);
164 
165  //- Join two strings with a path separator ('/' by default).
166  // No separator is added if either argument is an empty string or
167  // if the arguments already had the path separator at the junction.
168  // Invalid characters are \em not stripped (ie, retained).
169  static fileName concat
170  (
171  const std::string& s1,
172  const std::string& s2,
173  const char delim = '/'
174  );
175 
176  //- This is a specialized (possibly slower) version of compare()
177  //- that ignores duplicate or trailing slashes.
178  static bool equals(const std::string& s1, const std::string& s2);
179 
180  //- Strip invalid characters
181  inline void stripInvalid();
182 
183  //- Cleanup filename string, possibly applies other transformations
184  //- such as changing the path separator etc.
185  //
186  // Changes back-slash to forward-slash path separator,
187  // while preserving windows UNC:
188  // \verbatim
189  // \\server\abc\def --> \\server/abc/def
190  // \endverbatim
191  //
192  // Removes trailing slash:
193  // \verbatim
194  // / --> /
195  // /abc/ --> /abc
196  // \endverbatim
197  //
198  // Removes repeated slashes, but preserves UNC:
199  // \verbatim
200  // /abc////def --> /abc/def
201  // \\server\abc////def --> \\server/abc/def
202  // \endverbatim
203  //
204  // Removes \c "/./" (current directory), except for leading one:
205  // \verbatim
206  // /abc/def/./ghi/. --> /abc/def/ghi
207  // abc/def/./ --> abc/def
208  // ./abc/ --> ./abc
209  // \endverbatim
210  //
211  // Removes \c "/../" (parent directory), except for leading one:
212  // \verbatim
213  // /abc/def/../ghi/jkl/nmo/.. --> /abc/ghi/jkl
214  // abc/../def/ghi/../jkl --> abc/../def/jkl
215  // \endverbatim
216  // .
217  //
218  // \return True if the content changed
219  static bool clean(std::string& str);
220 
221  //- Cleanup filename (inplace)
222  // \return True if the content changed
223  bool clean();
224 
225 
226  // Interrogation
227 
228  //- Return the directory entry type:
229  //- UNDEFINED, FILE, DIRECTORY (or SYMLINK).
230  //
231  // \param followLink when false it will return SYMLINK for a symlink
232  // rather than following it.
233  // \param checkGzip add an additional test for a gzip FILE
234  Type type(bool followLink=true, bool checkGzip=false) const;
235 
236  //- Return true if filename starts with a '/' or '\\'
237  //- or (windows-only) with a filesystem-root
238  inline static bool isAbsolute(const std::string& str);
239 
240  //- Return true if filename is absolute,
241  //- which means it starts with a '/' or '\\'
242  //- or (windows-only) with a filesystem-root
243  inline bool isAbsolute() const;
244 
245  //- Convert from relative to absolute
246  fileName& toAbsolute();
247 
248  //- Return true if string ends with "~", ".bak", ".old", ".save"
249  static bool isBackup(const std::string& str);
250 
251  //- Return true if file name ends with "~", ".bak", ".old", ".save"
252  inline bool isBackup() const;
253 
254 
255  // Decomposition
256 
257  //- Return directory path name (part before last /)
258  // The result normally corresponds to a Foam::fileName
259  //
260  // Behaviour compared to /usr/bin/dirname:
261  // \verbatim
262  // input path() dirname
263  // ----- ------ -------
264  // "" "." "."
265  // "abc" "." "."
266  // "/" "/" "/"
267  // "/abc" "/" "/"
268  // "abc/def" "abc" "abc"
269  // "/abc/def" "/abc" "/abc"
270  // "/abc/def/" "/abc/def" "/abc"
271  // "/abc/../def" "/abc/.." "/abc/.."
272  // \endverbatim
273  inline static std::string path(const std::string& str);
274 
275  //- Return directory path name (part before last /)
276  inline fileName path() const;
277 
278  //- Remove leading path, return true if string changed.
279  using string::remove_path;
280 
281  //- True if it contains a '/' character
282  inline bool has_path() const;
283 
284 
285  //- Return basename (part beyond last /), including its extension
286  // The result normally corresponds to a Foam::word
287  //
288  // Behaviour compared to /usr/bin/basename:
289  // \verbatim
290  // input name() basename
291  // ----- ------ --------
292  // "" "" ""
293  // "abc" "abc" "abc"
294  // "/" "" "/"
295  // "/abc" "abc" "abc"
296  // "abc/def" "def" "def"
297  // "/abc/def" "def" "def"
298  // "/abc/def/" "" "def"
299  // "/abc/../def" "def" "def"
300  // \endverbatim
301  inline static std::string name(const std::string& str);
302 
303  //- Return basename (part beyond last /), including its extension
304  inline word name() const;
305 
306  //- Replace basename (part beyond last /) with a new name
307  fileName& replace_name(const word& newName);
308 
309  //- Return the basename, without extension
310  // The result normally corresponds to a Foam::word
311  static std::string stem(const std::string& str);
312 
313  //- Return basename, without extension
314  inline word stem() const;
315 
316 
317  //- Return file name extension (part after last .)
318  inline word ext() const;
319 
320  //- Append a '.' and the ending, and return the object.
321  // The '.' and ending will not be added when the ending is empty,
322  // or when the file name is empty or ended with a '/'.
323  inline fileName& ext(const word& ending);
324 
325  //- Remove extension (if any) and append a new one
326  inline fileName& replace_ext(const word& ending);
327 
328  //- Return file name without extension (part before last .)
329  inline fileName lessExt() const;
330 
331  //- Remove extension, returning true if string changed.
332  using string::remove_ext;
333 
334  //- Various checks for extensions
335  using string::has_ext;
336 
337 
338  //- Return a relative name by stripping off the parent directory
339  //- where possible.
340  //
341  // \param parent the parent directory
342  // \param caseTag replace the parent with <case> for later
343  // use with expand(), or prefix <case> if the file name was
344  // not an absolute location
346  (
347  const fileName& parent,
348  const bool caseTag = false
349  ) const;
350 
351 
352  //- Return path components as wordList
353  //
354  // Behaviour:
355  // \verbatim
356  // input components()
357  // ----- ------------
358  // "" ()
359  // "." (".")
360  // "abc" ("abc")
361  // "/abc" ("abc")
362  // "abc/def" ("abc", "def")
363  // "/abc/def" ("abc", "def")
364  // "/abc/def/" ("abc", "def")
365  // \endverbatim
366  wordList components(const char delim = '/') const;
367 
368  //- Return a single component of the path or empty if out of range
369  // The location \c npos returns the last component
370  word component(const size_type cmpt, const char delim = '/') const;
371 
372 
373  // Member Operators
374 
375  // Assignment
376 
377  //- Copy assignment, no character validation required
378  // Self-assignment is a no-op.
379  inline fileName& operator=(const fileName& str);
380 
381  //- Move assignment, no character validation required
382  // Self-assignment is a no-op.
383  inline fileName& operator=(fileName&& str);
384 
385  //- Copy assignment, no character validation required
386  inline fileName& operator=(const word& str);
387 
388  //- Move assignment, no character validation required
389  inline fileName& operator=(word&& str);
390 
391  //- Copy assignment, stripping invalid characters
392  inline fileName& operator=(const string& str);
393 
394  //- Move assignment, stripping invalid characters
395  inline fileName& operator=(string&& str);
396 
397  //- Copy assignment, stripping invalid characters
398  inline fileName& operator=(const std::string& str);
399 
400  //- Move assignment, stripping invalid characters
401  inline fileName& operator=(std::string&& str);
402 
403  //- Copy, stripping invalid characters
404  inline fileName& operator=(const char* str);
405 
406 
407  // Other Operators
408 
409  //- Append a path element with '/' separator.
410  // No '/' separator is added if this or the argument are empty.
411  fileName& operator/=(const string& other);
412 
413 
414  // Housekeeping
415 
416  //- Same as has_path()
417  bool hasPath() const { return has_path(); }
418 
419  //- Same as remove_path()
420  bool removePath() { return remove_path(); }
421 
422  //- Same as has_ext()
423  bool hasExt() const { return has_ext(); }
424 
425  //- Same as has_ext()
426  bool hasExt(const std::string& s) const { return has_ext(s); }
427 
428  //- Same as remove_ext()
429  bool removeExt() { return remove_ext(); }
430 
431  //- Same as stem()
432  static std::string nameLessExt(const std::string& s)
433  {
434  return fileName::stem(s);
435  }
436 
437  //- Same as stem()
438  word nameLessExt() const { return stem(); }
439 
440  //- Deprecated(2017-03) return basename, optionally without extension
441  // \deprecated(2017-03) - use name() or stem() methods
442  // which describe their behaviour explicitly
443  word name(const bool noExt) const
444  {
445  return noExt ? stem() : name();
446  }
447 };
448 
449 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
450 
451 // IOstream Operators
452 
453 //- Read operator
454 Istream& operator>>(Istream& is, fileName& val);
455 
456 //- Write operator
457 Ostream& operator<<(Ostream& os, const fileName& val);
458 
459 
460 // Global Operators
461 
462 //- Assemble words and fileNames as pathnames by adding a '/' separator.
463 // No '/' separator is added if either argument is an empty string.
464 fileName operator/(const string& s1, const string& s2);
465 
466 
467 //- Recursively search the given directory for the file
468 // returning the path relative to the directory or
469 // fileName::null if not found
470 fileName search(const word& file, const fileName& directory);
471 
472 
473 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
474 
475 } // End namespace Foam
476 
477 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
478 
479 #include "fileNameI.H"
480 
481 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
482 
483 #endif
484 
485 // ************************************************************************* //
A symbolic link.
Definition: fileName.H:85
static int debug
Debugging.
Definition: fileName.H:100
A class for handling file names.
Definition: fileName.H:71
fileName & operator/=(const string &other)
Append a path element with &#39;/&#39; separator.
Definition: fileName.C:575
bool clean()
Cleanup filename (inplace)
Definition: fileName.C:383
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:586
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:64
static const fileName null
An empty fileName.
Definition: fileName.H:110
Undefined type.
Definition: fileName.H:82
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:95
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:550
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:441
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:83
word name() const
Return basename (part beyond last /), including its extension.
Definition: fileNameI.H:205
bool removePath()
Same as remove_path()
Definition: fileName.H:558
Same as symlink.
Definition: fileName.H:86
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:99
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:530
bool hasPath() const
Same as has_path()
Definition: fileName.H:553
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:417
Ostream & operator<<(Ostream &, const boundaryPatch &p)
Write boundaryPatch as dictionary entries (without surrounding braces)
Definition: boundaryPatch.C:76
List< word > wordList
List of word.
Definition: fileName.H:58
bool removeExt()
Same as remove_ext()
Definition: fileName.H:573
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:105
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:563
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:640
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:80
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