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