1 : // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : // This file contains utility functions for dealing with the local
6 : // filesystem.
7 :
8 : #ifndef BASE_FILE_UTIL_H_
9 : #define BASE_FILE_UTIL_H_
10 :
11 : #include "build/build_config.h"
12 :
13 : #if defined(OS_WIN)
14 : #include <windows.h>
15 : #elif defined(ANDROID)
16 : #include <sys/stat.h>
17 : #elif defined(OS_POSIX)
18 : #include <sys/types.h>
19 : #include <fts.h>
20 : #include <sys/stat.h>
21 : #endif
22 :
23 : #include <stdio.h>
24 :
25 : #include <stack>
26 : #include <string>
27 : #include <vector>
28 :
29 : #include "base/basictypes.h"
30 : #include "base/scoped_ptr.h"
31 : #include "base/file_path.h"
32 :
33 : namespace base {
34 : class Time;
35 : }
36 :
37 : namespace file_util {
38 :
39 : //-----------------------------------------------------------------------------
40 : // Functions that operate purely on a path string w/o touching the filesystem:
41 :
42 : // Returns a vector of all of the components of the provided path.
43 : void PathComponents(const FilePath& path,
44 : std::vector<FilePath::StringType>* components);
45 : #if defined(OS_WIN)
46 : // Deprecated temporary compatibility function.
47 : void PathComponents(const std::wstring& path,
48 : std::vector<std::wstring>* components);
49 : #endif
50 :
51 : // Returns true if the given path ends with a path separator character.
52 : bool EndsWithSeparator(const FilePath& path);
53 : // These two versions are both deprecated. TODO(estade): remove them.
54 : bool EndsWithSeparator(std::wstring* path);
55 : bool EndsWithSeparator(const std::wstring& path);
56 :
57 : // Makes sure that |path| ends with a separator IFF path is a directory that
58 : // exists. Returns true if |path| is an existing directory, false otherwise.
59 : bool EnsureEndsWithSeparator(FilePath* path);
60 :
61 : // Modifies a string by trimming all trailing separators from the end.
62 : // Deprecated. FilePath does this automatically, and if it's constructed from a
63 : // path with a trailing separator, StripTrailingSeparators() may be used.
64 : void TrimTrailingSeparator(std::wstring* dir);
65 :
66 : // Strips the topmost directory from the end of 'dir'. Assumes 'dir' does not
67 : // refer to a file.
68 : // If 'dir' is a root directory, return without change.
69 : // Deprecated. Use FilePath::DirName instead.
70 : void UpOneDirectory(std::wstring* dir);
71 : // Strips the topmost directory from the end of 'dir'. Assumes 'dir' does not
72 : // refer to a file.
73 : // If 'dir' is a root directory, the result becomes empty string.
74 : // Deprecated. Use FilePath::DirName instead.
75 : void UpOneDirectoryOrEmpty(std::wstring* dir);
76 :
77 : // Returns the filename portion of 'path', without any leading \'s or /'s.
78 : // Deprecated. Use FilePath::BaseName instead.
79 : std::wstring GetFilenameFromPath(const std::wstring& path);
80 :
81 : // Deprecated compatibility function. Use FilePath::Extension.
82 : FilePath::StringType GetFileExtensionFromPath(const FilePath& path);
83 : // Deprecated temporary compatibility function.
84 : std::wstring GetFileExtensionFromPath(const std::wstring& path);
85 :
86 : // Returns the directory component of a path, without the trailing
87 : // path separator, or an empty string on error. The function does not
88 : // check for the existence of the path, so if it is passed a directory
89 : // without the trailing \, it will interpret the last component of the
90 : // path as a file and chomp it. This does not support relative paths.
91 : // Examples:
92 : // path == "C:\pics\jojo.jpg", returns "C:\pics"
93 : // path == "C:\Windows\system32\", returns "C:\Windows\system32"
94 : // path == "C:\Windows\system32", returns "C:\Windows"
95 : std::wstring GetDirectoryFromPath(const std::wstring& path);
96 :
97 : // Appends new_ending to path, adding a separator between the two if necessary.
98 : void AppendToPath(std::wstring* path, const std::wstring& new_ending);
99 :
100 : // Convert provided relative path into an absolute path. Returns false on
101 : // error. On POSIX, this function fails if the path does not exist.
102 : bool AbsolutePath(FilePath* path);
103 : // Deprecated temporary compatibility function.
104 : bool AbsolutePath(std::wstring* path);
105 :
106 : // Returns true if |parent| contains |child|. Both paths are converted to
107 : // absolute paths before doing the comparison.
108 : bool ContainsPath(const FilePath& parent, const FilePath& child);
109 :
110 : // Deprecated compatibility function. Use FilePath::InsertBeforeExtension.
111 : void InsertBeforeExtension(FilePath* path, const FilePath::StringType& suffix);
112 :
113 : // Deprecated compatibility function. Use FilePath::ReplaceExtension.
114 : void ReplaceExtension(FilePath* file_name,
115 : const FilePath::StringType& extension);
116 :
117 : #if defined(OS_WIN)
118 : // Deprecated temporary compatibility functions.
119 : void InsertBeforeExtension(std::wstring* path, const std::wstring& suffix);
120 : void ReplaceExtension(std::wstring* file_name, const std::wstring& extension);
121 : #endif
122 :
123 : // Replaces characters in 'file_name' that are illegal for file names with
124 : // 'replace_char'. 'file_name' must not be a full or relative path, but just the
125 : // file name component. Any leading or trailing whitespace in 'file_name' is
126 : // removed.
127 : // Example:
128 : // file_name == "bad:file*name?.txt", changed to: "bad-file-name-.txt" when
129 : // 'replace_char' is '-'.
130 : void ReplaceIllegalCharacters(std::wstring* file_name, int replace_char);
131 :
132 : //-----------------------------------------------------------------------------
133 : // Functions that involve filesystem access or modification:
134 :
135 : // created on or after the given |file_time|. Doesn't count ".." or ".".
136 : //
137 : // Note for POSIX environments: a file created before |file_time|
138 : // can be mis-detected as a newer file due to low precision of
139 : // timestmap of file creation time. If you need to avoid such
140 : // mis-detection perfectly, you should wait one second before
141 : // obtaining |file_time|.
142 : int CountFilesCreatedAfter(const FilePath& path,
143 : const base::Time& file_time);
144 :
145 : // Deletes the given path, whether it's a file or a directory.
146 : // If it's a directory, it's perfectly happy to delete all of the
147 : // directory's contents. Passing true to recursive deletes
148 : // subdirectories and their contents as well.
149 : // Returns true if successful, false otherwise.
150 : //
151 : // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
152 : // TO "rm -rf", SO USE WITH CAUTION.
153 : bool Delete(const FilePath& path, bool recursive);
154 : // Deprecated temporary compatibility function.
155 : bool Delete(const std::wstring& path, bool recursive);
156 :
157 : // Moves the given path, whether it's a file or a directory.
158 : // If a simple rename is not possible, such as in the case where the paths are
159 : // on different volumes, this will attempt to copy and delete. Returns
160 : // true for success.
161 : bool Move(const FilePath& from_path, const FilePath& to_path);
162 : // Deprecated temporary compatibility function.
163 : bool Move(const std::wstring& from_path, const std::wstring& to_path);
164 :
165 : // Copies a single file. Use CopyDirectory to copy directories.
166 : bool CopyFile(const FilePath& from_path, const FilePath& to_path);
167 : // Deprecated temporary compatibility function.
168 : bool CopyFile(const std::wstring& from_path, const std::wstring& to_path);
169 :
170 : // Copies the given path, and optionally all subdirectories and their contents
171 : // as well.
172 : // If there are files existing under to_path, always overwrite.
173 : // Returns true if successful, false otherwise.
174 : // Dont't use wildcards on the names, it may stop working without notice.
175 : //
176 : // If you only need to copy a file use CopyFile, it's faster.
177 : bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
178 : bool recursive);
179 : // Deprecated temporary compatibility function.
180 : bool CopyDirectory(const std::wstring& from_path, const std::wstring& to_path,
181 : bool recursive);
182 :
183 : // Returns true if the given path exists on the local filesystem,
184 : // false otherwise.
185 : bool PathExists(const FilePath& path);
186 : // Deprecated temporary compatibility function.
187 : bool PathExists(const std::wstring& path);
188 :
189 : // Returns true if the given path is writable by the user, false otherwise.
190 : bool PathIsWritable(const FilePath& path);
191 : // Deprecated temporary compatibility function.
192 : bool PathIsWritable(const std::wstring& path);
193 :
194 : // Returns true if the given path exists and is a directory, false otherwise.
195 : bool DirectoryExists(const FilePath& path);
196 : // Deprecated temporary compatibility function.
197 : bool DirectoryExists(const std::wstring& path);
198 :
199 : #if defined(OS_WIN)
200 : // Gets the creation time of the given file (expressed in the local timezone),
201 : // and returns it via the creation_time parameter. Returns true if successful,
202 : // false otherwise.
203 : bool GetFileCreationLocalTime(const std::wstring& filename,
204 : LPSYSTEMTIME creation_time);
205 :
206 : // Same as above, but takes a previously-opened file handle instead of a name.
207 : bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
208 : LPSYSTEMTIME creation_time);
209 : #endif // defined(OS_WIN)
210 :
211 : // Returns true if the contents of the two files given are equal, false
212 : // otherwise. If either file can't be read, returns false.
213 : bool ContentsEqual(const FilePath& filename1,
214 : const FilePath& filename2);
215 : // Deprecated temporary compatibility function.
216 : bool ContentsEqual(const std::wstring& filename1,
217 : const std::wstring& filename2);
218 :
219 : // Read the file at |path| into |contents|, returning true on success.
220 : // Useful for unit tests.
221 : bool ReadFileToString(const FilePath& path, std::string* contents);
222 : // Deprecated version.
223 : bool ReadFileToString(const std::wstring& path, std::string* contents);
224 :
225 : #if defined(OS_POSIX)
226 : // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
227 : // in |buffer|. This function is protected against EINTR and partial reads.
228 : // Returns true iff |bytes| bytes have been successfuly read from |fd|.
229 : bool ReadFromFD(int fd, char* buffer, size_t bytes);
230 : #endif // defined(OS_POSIX)
231 :
232 : #if defined(OS_WIN)
233 : // Resolve Windows shortcut (.LNK file)
234 : // Argument path specifies a valid LNK file. On success, return true and put
235 : // the URL into path. If path is a invalid .LNK file, return false.
236 : bool ResolveShortcut(FilePath* path);
237 : // Deprecated temporary compatibility function.
238 : bool ResolveShortcut(std::wstring* path);
239 :
240 : // Create a Windows shortcut (.LNK file)
241 : // This method creates a shortcut link using the information given. Ensure
242 : // you have initialized COM before calling into this function. 'source'
243 : // and 'destination' parameters are required, everything else can be NULL.
244 : // 'source' is the existing file, 'destination' is the new link file to be
245 : // created; for best results pass the filename with the .lnk extension.
246 : // The 'icon' can specify a dll or exe in which case the icon index is the
247 : // resource id.
248 : // Note that if the shortcut exists it will overwrite it.
249 : bool CreateShortcutLink(const wchar_t *source, const wchar_t *destination,
250 : const wchar_t *working_dir, const wchar_t *arguments,
251 : const wchar_t *description, const wchar_t *icon,
252 : int icon_index);
253 :
254 : // Update a Windows shortcut (.LNK file). This method assumes the shortcut
255 : // link already exists (otherwise false is returned). Ensure you have
256 : // initialized COM before calling into this function. Only 'destination'
257 : // parameter is required, everything else can be NULL (but if everything else
258 : // is NULL no changes are made to the shortcut). 'destination' is the link
259 : // file to be updated. For best results pass the filename with the .lnk
260 : // extension.
261 : bool UpdateShortcutLink(const wchar_t *source, const wchar_t *destination,
262 : const wchar_t *working_dir, const wchar_t *arguments,
263 : const wchar_t *description, const wchar_t *icon,
264 : int icon_index);
265 :
266 : // Return true if the given directory is empty
267 : bool IsDirectoryEmpty(const std::wstring& dir_path);
268 :
269 : // Copy from_path to to_path recursively and then delete from_path recursively.
270 : // Returns true if all operations succeed.
271 : // This function simulates Move(), but unlike Move() it works across volumes.
272 : // This fuction is not transactional.
273 : bool CopyAndDeleteDirectory(const FilePath& from_path,
274 : const FilePath& to_path);
275 : #endif
276 :
277 : // Get the temporary directory provided by the system.
278 : bool GetTempDir(FilePath* path);
279 : // Deprecated temporary compatibility function.
280 : bool GetTempDir(std::wstring* path);
281 : // Get a temporary directory for shared memory files.
282 : // Only useful on POSIX; redirects to GetTempDir() on Windows.
283 : bool GetShmemTempDir(FilePath* path);
284 :
285 : // Creates a temporary file. The full path is placed in |path|, and the
286 : // function returns true if was successful in creating the file. The file will
287 : // be empty and all handles closed after this function returns.
288 : // TODO(erikkay): rename this function and track down all of the callers.
289 : // (Clarification of erik's comment: the intent is to rename the BlahFileName()
290 : // calls into BlahFile(), since they create temp files (not temp filenames).)
291 : bool CreateTemporaryFileName(FilePath* path);
292 : // Deprecated temporary compatibility function.
293 : bool CreateTemporaryFileName(std::wstring* temp_file);
294 :
295 : // Create and open a temporary file. File is opened for read/write.
296 : // The full path is placed in |path|, and the function returns true if
297 : // was successful in creating and opening the file.
298 : FILE* CreateAndOpenTemporaryFile(FilePath* path);
299 : // Like above but for shmem files. Only useful for POSIX.
300 : FILE* CreateAndOpenTemporaryShmemFile(FilePath* path);
301 :
302 : // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
303 : FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path);
304 :
305 : // Same as CreateTemporaryFileName but the file is created in |dir|.
306 : bool CreateTemporaryFileNameInDir(const std::wstring& dir,
307 : std::wstring* temp_file);
308 :
309 : // Create a new directory under TempPath. If prefix is provided, the new
310 : // directory name is in the format of prefixyyyy.
311 : // NOTE: prefix is ignored in the POSIX implementation.
312 : // TODO(erikkay): is this OK?
313 : // If success, return true and output the full path of the directory created.
314 : bool CreateNewTempDirectory(const FilePath::StringType& prefix,
315 : FilePath* new_temp_path);
316 : // Deprecated temporary compatibility function.
317 : bool CreateNewTempDirectory(const std::wstring& prefix,
318 : std::wstring* new_temp_path);
319 :
320 : // Creates a directory, as well as creating any parent directories, if they
321 : // don't exist. Returns 'true' on successful creation, or if the directory
322 : // already exists.
323 : bool CreateDirectory(const FilePath& full_path);
324 : // Deprecated temporary compatibility function.
325 : bool CreateDirectory(const std::wstring& full_path);
326 :
327 : // Returns the file size. Returns true on success.
328 : bool GetFileSize(const FilePath& file_path, int64* file_size);
329 : // Deprecated temporary compatibility function.
330 : bool GetFileSize(const std::wstring& file_path, int64* file_size);
331 :
332 : // Used to hold information about a given file path. See GetFileInfo below.
333 : struct FileInfo {
334 : // The size of the file in bytes. Undefined when is_directory is true.
335 : int64 size;
336 :
337 : // True if the file corresponds to a directory.
338 : bool is_directory;
339 :
340 : // Add additional fields here as needed.
341 : };
342 :
343 : // Returns information about the given file path.
344 : bool GetFileInfo(const FilePath& file_path, FileInfo* info);
345 : // Deprecated temporary compatibility function.
346 : bool GetFileInfo(const std::wstring& file_path, FileInfo* info);
347 :
348 : // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
349 : FILE* OpenFile(const FilePath& filename, const char* mode);
350 : // Deprecated temporary compatibility functions.
351 : FILE* OpenFile(const std::string& filename, const char* mode);
352 : FILE* OpenFile(const std::wstring& filename, const char* mode);
353 :
354 : // Closes file opened by OpenFile. Returns true on success.
355 : bool CloseFile(FILE* file);
356 :
357 : // Truncates an open file to end at the location of the current file pointer.
358 : // This is a cross-platform analog to Windows' SetEndOfFile() function.
359 : bool TruncateFile(FILE* file);
360 :
361 : // Reads the given number of bytes from the file into the buffer. Returns
362 : // the number of read bytes, or -1 on error.
363 : int ReadFile(const FilePath& filename, char* data, int size);
364 : // Deprecated temporary compatibility function.
365 : int ReadFile(const std::wstring& filename, char* data, int size);
366 :
367 : // Writes the given buffer into the file, overwriting any data that was
368 : // previously there. Returns the number of bytes written, or -1 on error.
369 : int WriteFile(const FilePath& filename, const char* data, int size);
370 : // Deprecated temporary compatibility function.
371 : int WriteFile(const std::wstring& filename, const char* data, int size);
372 :
373 : // Gets the current working directory for the process.
374 : bool GetCurrentDirectory(FilePath* path);
375 : // Deprecated temporary compatibility function.
376 : bool GetCurrentDirectory(std::wstring* path);
377 :
378 : // Sets the current working directory for the process.
379 : bool SetCurrentDirectory(const FilePath& path);
380 : // Deprecated temporary compatibility function.
381 : bool SetCurrentDirectory(const std::wstring& current_directory);
382 :
383 : // A class to handle auto-closing of FILE*'s.
384 : class ScopedFILEClose {
385 : public:
386 0 : inline void operator()(FILE* x) const {
387 0 : if (x) {
388 0 : fclose(x);
389 : }
390 0 : }
391 : };
392 :
393 : typedef scoped_ptr_malloc<FILE, ScopedFILEClose> ScopedFILE;
394 :
395 : // A class for enumerating the files in a provided path. The order of the
396 : // results is not guaranteed.
397 : //
398 : // DO NOT USE FROM THE MAIN THREAD of your application unless it is a test
399 : // program where latency does not matter. This class is blocking.
400 : class FileEnumerator {
401 : public:
402 : #if defined(OS_WIN)
403 : typedef WIN32_FIND_DATA FindInfo;
404 : #elif defined(OS_POSIX)
405 : typedef struct {
406 : struct stat stat;
407 : std::string filename;
408 : } FindInfo;
409 : #endif
410 :
411 : enum FILE_TYPE {
412 : FILES = 0x1,
413 : DIRECTORIES = 0x2,
414 : FILES_AND_DIRECTORIES = 0x3
415 : };
416 :
417 : // |root_path| is the starting directory to search for. It may or may not end
418 : // in a slash.
419 : //
420 : // If |recursive| is true, this will enumerate all matches in any
421 : // subdirectories matched as well. It does a breadth-first search, so all
422 : // files in one directory will be returned before any files in a
423 : // subdirectory.
424 : //
425 : // |file_type| specifies whether the enumerator should match files,
426 : // directories, or both.
427 : //
428 : // |pattern| is an optional pattern for which files to match. This
429 : // works like shell globbing. For example, "*.txt" or "Foo???.doc".
430 : // However, be careful in specifying patterns that aren't cross platform
431 : // since the underlying code uses OS-specific matching routines. In general,
432 : // Windows matching is less featureful than others, so test there first.
433 : // If unspecified, this will match all files.
434 : // NOTE: the pattern only matches the contents of root_path, not files in
435 : // recursive subdirectories.
436 : // TODO(erikkay): Fix the pattern matching to work at all levels.
437 : FileEnumerator(const FilePath& root_path,
438 : bool recursive,
439 : FileEnumerator::FILE_TYPE file_type);
440 : FileEnumerator(const FilePath& root_path,
441 : bool recursive,
442 : FileEnumerator::FILE_TYPE file_type,
443 : const FilePath::StringType& pattern);
444 : ~FileEnumerator();
445 :
446 : // Returns an empty string if there are no more results.
447 : FilePath Next();
448 :
449 : // Write the file info into |info|.
450 : void GetFindInfo(FindInfo* info);
451 :
452 : private:
453 : FilePath root_path_;
454 : bool recursive_;
455 : FILE_TYPE file_type_;
456 : FilePath pattern_; // Empty when we want to find everything.
457 :
458 : // Set to true when there is a find operation open. This way, we can lazily
459 : // start the operations when the caller calls Next().
460 : bool is_in_find_op_;
461 :
462 : // A stack that keeps track of which subdirectories we still need to
463 : // enumerate in the breadth-first search.
464 : std::stack<FilePath> pending_paths_;
465 :
466 : #if defined(OS_WIN)
467 : WIN32_FIND_DATA find_data_;
468 : HANDLE find_handle_;
469 : #elif defined(ANDROID)
470 : void *fts_;
471 : #elif defined(OS_POSIX)
472 : FTS* fts_;
473 : FTSENT* fts_ent_;
474 : #endif
475 :
476 : DISALLOW_EVIL_CONSTRUCTORS(FileEnumerator);
477 : };
478 :
479 : class MemoryMappedFile {
480 : public:
481 : // The default constructor sets all members to invalid/null values.
482 : MemoryMappedFile();
483 : ~MemoryMappedFile();
484 :
485 : // Opens an existing file and maps it into memory. Access is restricted to
486 : // read only. If this object already points to a valid memory mapped file
487 : // then this method will fail and return false. If it cannot open the file,
488 : // the file does not exist, or the memory mapping fails, it will return false.
489 : // Later we may want to allow the user to specify access.
490 : bool Initialize(const FilePath& file_name);
491 :
492 : const uint8* data() const { return data_; }
493 : size_t length() const { return length_; }
494 :
495 : // Is file_ a valid file handle that points to an open, memory mapped file?
496 : bool IsValid();
497 :
498 : private:
499 : // Map the file to memory, set data_ to that memory address. Return true on
500 : // success, false on any kind of failure. This is a helper for Initialize().
501 : bool MapFileToMemory(const FilePath& file_name);
502 :
503 : // Closes all open handles. Later we may want to make this public.
504 : void CloseHandles();
505 :
506 : #if defined(OS_WIN)
507 : HANDLE file_;
508 : HANDLE file_mapping_;
509 : #elif defined(OS_POSIX)
510 : // The file descriptor.
511 : int file_;
512 : #endif
513 : uint8* data_;
514 : size_t length_;
515 :
516 : DISALLOW_COPY_AND_ASSIGN(MemoryMappedFile);
517 : };
518 :
519 : // Renames a file using the SHFileOperation API to ensure that the target file
520 : // gets the correct default security descriptor in the new path.
521 : bool RenameFileAndResetSecurityDescriptor(
522 : const FilePath& source_file_path,
523 : const FilePath& target_file_path);
524 :
525 : } // namespace file_util
526 :
527 : #endif // BASE_FILE_UTIL_H_
|