HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
UT_FileUtil.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: UT_FileUtil.h ( UT Library, C++)
7  *
8  * COMMENTS: This verb class provides a wide assortment of
9  * file utility functions.
10  */
11 
12 #ifndef __UT_FileUtil__
13 #define __UT_FileUtil__
14 
15 #include "UT_API.h"
16 #include "UT_Assert.h"
17 #include "UT_NTUtil.h" // for mode_t
18 #include <SYS/SYS_Compiler.h>
19 #include <SYS/SYS_Types.h>
20 #include <SYS/SYS_Stdio.h>
21 
22 #include <iosfwd>
23 #include <stdio.h>
24 #include <time.h>
25 
26 class UT_String;
27 class UT_WorkBuffer;
28 class UT_FileStat;
29 
30 // Here are flags used the by the file utility functions:
31 // If this is set, the showPrompt will be called before any destructive
32 // action.
33 #define UT_FILEUTIL_PROMPT 1
34 // If this is set, the original directory will be included in the
35 // sweep.
36 #define UT_FILEUTIL_INCLUSIVE 2
37 
38 // The standard return code is 0 for success, negative for failure.
39 // An appropriate error is passed to the error method which can
40 // be overridden to do something more interesting than dumping to
41 // the console.
43 {
44 public:
45  enum UT_RemoveDepth { IF_EMPTY, ALL_CONTENTS };
46 
47 
49  virtual ~UT_FileUtil() {}
50 
51  UT_FileUtil(const UT_FileUtil &) = delete;
52  UT_FileUtil &operator=(const UT_FileUtil &) = delete;
53 
54  /// Returns the file size of that file in the given path. Returns -1 on
55  /// error.
56  static int64 getFileSize(const char *path);
57 
58  /// Returns the file modification time of the file in the given path.
59  /// Returns -1 on error.
60  static time_t getFileModTime(const char *path);
61 
62  /// Returns the latest file modification time recusively of all files
63  /// in the given path including the path itself. If the given path
64  /// can be a regular file.
65  ///
66  /// If you've already statted the file in question, you can pass it as an
67  /// argument to avoid an additional stat call internally.
68  ///
69  /// Returns -1 if no timestamps can be retrieved.
70  static time_t getRecursiveDirMaxModTime(const char *path);
71  static time_t getRecursiveDirMaxModTime(const char *path, const UT_FileStat &fstat);
72 
73  /// Return the maximum number of file descriptors that are available
74  /// for this process.
75  static int getMaxFileDescriptors();
76 
77  /// Shorten the given path if possible. Only possibly has an effect on
78  /// Windows. Returns true if successful. Upon returning false, the contents
79  /// of result will be undefined.
80  static bool getShortPathName(UT_WorkBuffer &result,
81  const char *path);
82 
83  /// Follow the specified symbolic link to the contents, recursing if the
84  /// contents are themselves another symbolic link. This method will fail
85  /// if the specified path is not to a symbolic link, or if the link does
86  /// not point to an existing file when allow_dangling_link is false.
87  static int resolveSymbolicLinks(const char *path,
88  UT_WorkBuffer &contents,
89  bool allow_dangling_link = false);
90 
91  // Copies a file on disk from the source to the dest.
92  // This is only good for smallish files as we allocate a file size
93  // memory buffer.
94  static int copyFile(const char *srcname, const char *dstname,
95  std::ostream *error_os = nullptr);
96  // Recursively copy a directory
97  static int copyDir(const char *srcname, const char *dstname);
98  // Copies a file from a disk into a stream. This is good for
99  // building a .cpio archive.
100  static int copyFileToStream(const char *srcname, std::ostream &os);
101 
102  // Move a file, returns 0 on success.
103  static int moveFile(const char *srcname, const char *dstname);
104  // Delete a file
105  static int removeFile(const char *fname);
106 
107  // Delete a directory
108  static int removeDir(const char *dname,
109  UT_RemoveDepth depth = IF_EMPTY);
110 
111  /// Make a single directory. All leading path components must exist.
112  /// The function returns true if the path already exists or if the path was
113  /// made.
114  /// @param path @n The path to create
115  /// @param mode @n The unix file mode
116  /// @param ignore_umask @n
117  /// By default, the users umask will be used in conjunction with the
118  /// mode. This parameter will @b force the mode to be the given value.
119  static bool makeDir(const char *path, mode_t mode=0777,
120  bool ignore_umask = false);
121 
122  /// Make a directory and all the parent directories needed
123  /// @param path @n The path to create
124  /// @param mode @n The unix file mode
125  /// @param ignore_umask @n
126  /// By default, the users umask will be used in conjunction with the
127  /// mode. This parameter will @b force the mode to be the given value.
128  static bool makeDirs(const char *path, mode_t mode=0777,
129  bool ignore_umask = false);
130 
131  /// Locks a file for exclusive access. Will not return until the file lock
132  /// is achiveved or an error occurs. Equivalent to calling writeLockFile().
133  /// @returns true if the file lock succeeded, and false otherwise.
134  /// @note
135  /// - On Linux, if any file descriptor referring to this file is
136  /// closed, the lock will be automatically be closed. Be very careful!
137  /// - On Windows, this is NOT re-entrant (unlike Linux). Treat these locks
138  /// as NOT re-entrant unless you want deadlocking on Windows.
139  static bool lockFile(int fd);
140 
141  /// Unlocks a file that was locked for exclusive access with lockFile,
142  /// above.
143  /// Returns true if the unlock succeeded, and false otherwise.
144  static bool unlockFile(int fd);
145 
146  /// Locks a file for write access. Will not return until the file lock
147  /// is achiveved or an error occurs.
148  /// @returns true if the file lock succeeded, and false otherwise.
149  /// @note
150  /// - On Linux, if any file descriptor referring to this file is
151  /// closed, the lock will be automatically be closed. Be very careful!
152  /// - On Windows, this is NOT re-entrant (unlike Linux). Treat these locks
153  /// as NOT re-entrant unless you want deadlocking on Windows.
154  static bool writeLockFile(int fd);
155 
156  /// Locks a file for read access. Will not return until the file lock
157  /// is achiveved or an error occurs.
158  /// @returns true if the file lock succeeded, and false otherwise.
159  /// @note
160  /// - On Linux, if any file descriptor referring to this file is closed,
161  /// the lock will be automatically be closed. Be very careful!
162  /// - On Windows, this is NOT re-entrant (unlike Linux). Treat these locks
163  /// as NOT re-entrant unless you want deadlocking on Windows.
164  static bool readLockFile(int fd);
165 
166  // This navigates up the given path the specified number of levels.
167  // It adds a \0 at the correct slash, leaving path to be the
168  // proper path name.
169  // eg: upDirectory("foo/bar.vex", 1) = "foo"
170  // upDriectory("foo/bar/", 1) = "foo"
171  static void upDirectory(char *path, int levels);
172 
173  // This scans the (ascii) file fname for any line which starts
174  // with the prefix. If readonly is not true, it writes out a new
175  // version of the file lacking those lines. The return is the
176  // number of lines that would be removed, or negative if error.
177  static int removeLinesFromFile(const char *fname,
178  const char *prefix, int readonly = 0);
179 
180  // This is of the form
181  // removeOverrideFiles("d:/hsite/houdini5",
182  // "subnet/Sop",
183  // "foo.ds", "Dialog Script", UT_FILEUTIL_PROMPT);
184  // If the stripinfo is specified, it will do a removeLinesFromFile
185  // with stripinfo rather than delete.
186  int removeOverrideFiles(const char *newbasepath,
187  const char *relpath, const char *fname,
188  const char *english, int flags,
189  const char *stripinfo = 0);
190 
191  /// Parses the file in search of the given XML element and outputs
192  /// its contents into the string argument. Returns true uppon success
193  /// or false on failure.
194  static bool readXMLElementFromFile( const char * xml_file_path,
195  const char * element_name,
196  UT_String & element_data );
197 
198  // These are UI methods you can override to gain different behaviours
199  // for your instance:
200  // Severity is the same as UI_Manager::UI_ErrorType.
201  virtual void showError(const char *error, int severity = 2);
202  // 0 means Cancel, 1 OK.
203  virtual int showPrompt(const char *prompt);
204 
205 };
206 
208 
209 /// A class that allows you to create and lock a file for exclusive access.
210 /// When instances of this class go out of scope, the locked file is
211 /// automatically unlocked and closed.
213 {
214 public:
215  /// Construct without lock. Use lock() with filename to acquire one.
217  {
218  }
219 
220  /// Open and lock a file for exclusive reading and writing.
222  {
223  lock(filename, /*exclusive*/true);
224  }
225 
226  /// Open and lock a file for read-only (exclusive=false),
227  /// or for read-write (exclusive=true). If filename does not exist, then
228  /// it is opened as read-write.
229  UT_AutoFileLock(const char *filename, bool exclusive)
230  {
231  lock(filename, exclusive);
232  }
233 
235  {
236  unlock();
237  }
238 
239  /// Open and lock a file for read-only (exclusive=false),
240  /// or for read-write (exclusive=true). If filename does not exist, then
241  /// it is opened as read-write.
242  void lock(const char *filename, bool exclusive)
243  {
244  if (myFile)
245  {
246  UT_ASSERT(!"Can't relock");
247  return;
248  }
249 
250  // Try opening it as if it exists first, then try creating it.
251  myFile = SYSfopen(filename, exclusive ? "rb+" : "rb");
252  if (myFile)
253  {
254  if (exclusive)
255  myLockSucceeded = UT_FileUtil::writeLockFile(fileno(myFile));
256  else
257  myLockSucceeded = UT_FileUtil::readLockFile(fileno(myFile));
258  }
259  else
260  {
261  myFile = SYSfopen(filename, "wb+");
262  if (myFile)
263  myLockSucceeded = UT_FileUtil::writeLockFile(fileno(myFile));
264  else
265  myLockSucceeded = false;
266  }
267  }
268 
269  void unlock()
270  {
271  if (myFile)
272  {
273  if (myLockSucceeded)
274  {
275  UT_FileUtil::unlockFile(fileno(myFile));
276  myLockSucceeded = false;
277  }
278 
279  fclose(myFile);
280  myFile = nullptr;
281  }
282  }
283 
284  /// Get the file pointer for this locked file.
285  FILE *getFile() const
286  {
287  return myFile;
288  }
289 
290  /// Return whether the file is actually locked.
291  bool isLocked() const
292  {
293  return myLockSucceeded;
294  }
295 
296 private:
297  FILE *myFile = nullptr;
298  bool myLockSucceeded = false;
299 };
300 
301 #endif
302 
static bool unlockFile(int fd)
GLbitfield flags
Definition: glcorearb.h:1596
GT_API const UT_StringHolder filename
GLsizei const GLchar *const * path
Definition: glcorearb.h:3341
#define UT_API
Definition: UT_API.h:14
void lock(const char *filename, bool exclusive)
Definition: UT_FileUtil.h:242
**But if you need a result
Definition: thread.h:622
bool isLocked() const
Return whether the file is actually locked.
Definition: UT_FileUtil.h:291
< returns > If no error
Definition: snippets.dox:2
UT_AutoFileLock(UT_EmptyFileLock)
Construct without lock. Use lock() with filename to acquire one.
Definition: UT_FileUtil.h:216
long long int64
Definition: SYS_Types.h:116
#define SYS_NO_DISCARD_RESULT
Definition: SYS_Compiler.h:93
GLenum GLenum severity
Definition: glcorearb.h:2539
GLsizei levels
Definition: glcorearb.h:2224
FILE * getFile() const
Get the file pointer for this locked file.
Definition: UT_FileUtil.h:285
GLenum mode
Definition: glcorearb.h:99
GLint GLint GLsizei GLsizei GLsizei depth
Definition: glcorearb.h:476
static bool writeLockFile(int fd)
LeafData & operator=(const LeafData &)=delete
UT_AutoFileLock(const char *filename)
Open and lock a file for exclusive reading and writing.
Definition: UT_FileUtil.h:221
static bool readLockFile(int fd)
#define UT_ASSERT(ZZ)
Definition: UT_Assert.h:156
UT_AutoFileLock(const char *filename, bool exclusive)
Definition: UT_FileUtil.h:229
GLuint64 GLenum GLint fd
Definition: RE_OGL.h:262
virtual ~UT_FileUtil()
Definition: UT_FileUtil.h:49