1 // Copyright (c) 2012 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.
5 #include "base/file_util.h"
14 #include "base/files/file_path.h"
15 #include "base/logging.h"
16 #include "base/string_util.h"
17 #include "base/stringprintf.h"
18 #include "base/strings/string_piece.h"
19 #include "base/utf_string_conversions.h"
25 const FilePath::CharType kExtensionSeparator
= FILE_PATH_LITERAL('.');
27 // The maximum number of 'uniquified' files we will try to create.
28 // This is used when the filename we're trying to download is already in use,
29 // so we create a new unique filename by appending " (nnn)" before the
30 // extension, where 1 <= nnn <= kMaxUniqueFiles.
31 // Also used by code that cleans up said files.
32 static const int kMaxUniqueFiles
= 100;
38 bool g_bug108724_debug
= false;
40 void InsertBeforeExtension(FilePath
* path
, const FilePath::StringType
& suffix
) {
41 FilePath::StringType
& value
=
42 const_cast<FilePath::StringType
&>(path
->value());
44 const FilePath::StringType::size_type last_dot
=
45 value
.rfind(kExtensionSeparator
);
46 const FilePath::StringType::size_type last_separator
=
47 value
.find_last_of(FilePath::StringType(FilePath::kSeparators
));
49 if (last_dot
== FilePath::StringType::npos
||
50 (last_separator
!= std::wstring::npos
&& last_dot
< last_separator
)) {
51 // The path looks something like "C:\pics.old\jojo" or "C:\pics\jojo".
52 // We should just append the suffix to the entire path.
57 value
.insert(last_dot
, suffix
);
60 bool Move(const FilePath
& from_path
, const FilePath
& to_path
) {
61 if (from_path
.ReferencesParent() || to_path
.ReferencesParent())
63 return MoveUnsafe(from_path
, to_path
);
66 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
67 if (from_path
.ReferencesParent() || to_path
.ReferencesParent())
69 return CopyFileUnsafe(from_path
, to_path
);
72 bool ContentsEqual(const FilePath
& filename1
, const FilePath
& filename2
) {
73 // We open the file in binary format even if they are text files because
74 // we are just comparing that bytes are exactly same in both files and not
75 // doing anything smart with text formatting.
76 std::ifstream
file1(filename1
.value().c_str(),
77 std::ios::in
| std::ios::binary
);
78 std::ifstream
file2(filename2
.value().c_str(),
79 std::ios::in
| std::ios::binary
);
81 // Even if both files aren't openable (and thus, in some sense, "equal"),
82 // any unusable file yields a result of "false".
83 if (!file1
.is_open() || !file2
.is_open())
86 const int BUFFER_SIZE
= 2056;
87 char buffer1
[BUFFER_SIZE
], buffer2
[BUFFER_SIZE
];
89 file1
.read(buffer1
, BUFFER_SIZE
);
90 file2
.read(buffer2
, BUFFER_SIZE
);
92 if ((file1
.eof() != file2
.eof()) ||
93 (file1
.gcount() != file2
.gcount()) ||
94 (memcmp(buffer1
, buffer2
, file1
.gcount()))) {
99 } while (!file1
.eof() || !file2
.eof());
106 bool TextContentsEqual(const FilePath
& filename1
, const FilePath
& filename2
) {
107 std::ifstream
file1(filename1
.value().c_str(), std::ios::in
);
108 std::ifstream
file2(filename2
.value().c_str(), std::ios::in
);
110 // Even if both files aren't openable (and thus, in some sense, "equal"),
111 // any unusable file yields a result of "false".
112 if (!file1
.is_open() || !file2
.is_open())
116 std::string line1
, line2
;
117 getline(file1
, line1
);
118 getline(file2
, line2
);
120 // Check for mismatched EOF states, or any error state.
121 if ((file1
.eof() != file2
.eof()) ||
122 file1
.bad() || file2
.bad()) {
126 // Trim all '\r' and '\n' characters from the end of the line.
127 std::string::size_type end1
= line1
.find_last_not_of("\r\n");
128 if (end1
== std::string::npos
)
130 else if (end1
+ 1 < line1
.length())
131 line1
.erase(end1
+ 1);
133 std::string::size_type end2
= line2
.find_last_not_of("\r\n");
134 if (end2
== std::string::npos
)
136 else if (end2
+ 1 < line2
.length())
137 line2
.erase(end2
+ 1);
141 } while (!file1
.eof() || !file2
.eof());
146 bool ReadFileToString(const FilePath
& path
, std::string
* contents
) {
147 if (path
.ReferencesParent())
149 FILE* file
= OpenFile(path
, "rb");
156 while ((len
= fread(buf
, 1, sizeof(buf
), file
)) > 0) {
158 contents
->append(buf
, len
);
165 bool IsDirectoryEmpty(const FilePath
& dir_path
) {
166 FileEnumerator
files(dir_path
, false,
167 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
);
168 if (files
.Next().value().empty())
173 FILE* CreateAndOpenTemporaryFile(FilePath
* path
) {
175 if (!GetTempDir(&directory
))
178 return CreateAndOpenTemporaryFileInDir(directory
, path
);
181 bool GetFileSize(const FilePath
& file_path
, int64
* file_size
) {
182 base::PlatformFileInfo info
;
183 if (!GetFileInfo(file_path
, &info
))
185 *file_size
= info
.size
;
189 bool TouchFile(const FilePath
& path
,
190 const base::Time
& last_accessed
,
191 const base::Time
& last_modified
) {
192 int flags
= base::PLATFORM_FILE_OPEN
| base::PLATFORM_FILE_WRITE_ATTRIBUTES
;
195 // On Windows, FILE_FLAG_BACKUP_SEMANTICS is needed to open a directory.
196 if (DirectoryExists(path
))
197 flags
|= base::PLATFORM_FILE_BACKUP_SEMANTICS
;
200 const base::PlatformFile file
=
201 base::CreatePlatformFile(path
, flags
, NULL
, NULL
);
202 if (file
!= base::kInvalidPlatformFileValue
) {
203 bool result
= base::TouchPlatformFile(file
, last_accessed
, last_modified
);
204 base::ClosePlatformFile(file
);
211 bool SetLastModifiedTime(const FilePath
& path
,
212 const base::Time
& last_modified
) {
213 return TouchFile(path
, last_modified
, last_modified
);
216 bool CloseFile(FILE* file
) {
219 return fclose(file
) == 0;
222 bool TruncateFile(FILE* file
) {
225 long current_offset
= ftell(file
);
226 if (current_offset
== -1)
229 int fd
= _fileno(file
);
230 if (_chsize(fd
, current_offset
) != 0)
233 int fd
= fileno(file
);
234 if (ftruncate(fd
, current_offset
) != 0)
240 int GetUniquePathNumber(
241 const FilePath
& path
,
242 const FilePath::StringType
& suffix
) {
243 bool have_suffix
= !suffix
.empty();
244 if (!PathExists(path
) &&
245 (!have_suffix
|| !PathExists(FilePath(path
.value() + suffix
)))) {
250 for (int count
= 1; count
<= kMaxUniqueFiles
; ++count
) {
252 path
.InsertBeforeExtensionASCII(base::StringPrintf(" (%d)", count
));
253 if (!PathExists(new_path
) &&
254 (!have_suffix
|| !PathExists(FilePath(new_path
.value() + suffix
)))) {
262 int64
ComputeDirectorySize(const FilePath
& root_path
) {
263 int64 running_size
= 0;
264 FileEnumerator
file_iter(root_path
, true, FileEnumerator::FILES
);
265 for (FilePath current
= file_iter
.Next(); !current
.empty();
266 current
= file_iter
.Next()) {
267 FileEnumerator::FindInfo info
;
268 file_iter
.GetFindInfo(&info
);
270 LARGE_INTEGER li
= { info
.nFileSizeLow
, info
.nFileSizeHigh
};
271 running_size
+= li
.QuadPart
;
273 running_size
+= info
.stat
.st_size
;
279 ///////////////////////////////////////////////
282 // Note: the main logic is in file_util_<platform>.cc
284 bool FileEnumerator::ShouldSkip(const FilePath
& path
) {
285 FilePath::StringType basename
= path
.BaseName().value();
286 return basename
== FILE_PATH_LITERAL(".") ||
287 (basename
== FILE_PATH_LITERAL("..") &&
288 !(INCLUDE_DOT_DOT
& file_type_
));