Make certificate viewer a tab-modal dialog.
[chromium-blink-merge.git] / base / file_util.cc
blobe76c5c2fd9afc1958c991382e55e727bd0552726
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"
7 #if defined(OS_WIN)
8 #include <io.h>
9 #endif
10 #include <stdio.h>
12 #include <fstream>
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"
21 using base::FilePath;
23 namespace {
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;
34 } // namespace
36 namespace file_util {
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.
53 value.append(suffix);
54 return;
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())
62 return false;
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())
68 return false;
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())
84 return false;
86 const int BUFFER_SIZE = 2056;
87 char buffer1[BUFFER_SIZE], buffer2[BUFFER_SIZE];
88 do {
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()))) {
95 file1.close();
96 file2.close();
97 return false;
99 } while (!file1.eof() || !file2.eof());
101 file1.close();
102 file2.close();
103 return true;
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())
113 return false;
115 do {
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()) {
123 return false;
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)
129 line1.clear();
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)
135 line2.clear();
136 else if (end2 + 1 < line2.length())
137 line2.erase(end2 + 1);
139 if (line1 != line2)
140 return false;
141 } while (!file1.eof() || !file2.eof());
143 return true;
146 bool ReadFileToString(const FilePath& path, std::string* contents) {
147 if (path.ReferencesParent())
148 return false;
149 FILE* file = OpenFile(path, "rb");
150 if (!file) {
151 return false;
154 char buf[1 << 16];
155 size_t len;
156 while ((len = fread(buf, 1, sizeof(buf), file)) > 0) {
157 if (contents)
158 contents->append(buf, len);
160 CloseFile(file);
162 return true;
165 bool IsDirectoryEmpty(const FilePath& dir_path) {
166 FileEnumerator files(dir_path, false,
167 FileEnumerator::FILES | FileEnumerator::DIRECTORIES);
168 if (files.Next().value().empty())
169 return true;
170 return false;
173 FILE* CreateAndOpenTemporaryFile(FilePath* path) {
174 FilePath directory;
175 if (!GetTempDir(&directory))
176 return NULL;
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))
184 return false;
185 *file_size = info.size;
186 return true;
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;
194 #if defined(OS_WIN)
195 // On Windows, FILE_FLAG_BACKUP_SEMANTICS is needed to open a directory.
196 if (DirectoryExists(path))
197 flags |= base::PLATFORM_FILE_BACKUP_SEMANTICS;
198 #endif // OS_WIN
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);
205 return result;
208 return false;
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) {
217 if (file == NULL)
218 return true;
219 return fclose(file) == 0;
222 bool TruncateFile(FILE* file) {
223 if (file == NULL)
224 return false;
225 long current_offset = ftell(file);
226 if (current_offset == -1)
227 return false;
228 #if defined(OS_WIN)
229 int fd = _fileno(file);
230 if (_chsize(fd, current_offset) != 0)
231 return false;
232 #else
233 int fd = fileno(file);
234 if (ftruncate(fd, current_offset) != 0)
235 return false;
236 #endif
237 return true;
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)))) {
246 return 0;
249 FilePath new_path;
250 for (int count = 1; count <= kMaxUniqueFiles; ++count) {
251 new_path =
252 path.InsertBeforeExtensionASCII(base::StringPrintf(" (%d)", count));
253 if (!PathExists(new_path) &&
254 (!have_suffix || !PathExists(FilePath(new_path.value() + suffix)))) {
255 return count;
259 return -1;
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);
269 #if defined(OS_WIN)
270 LARGE_INTEGER li = { info.nFileSizeLow, info.nFileSizeHigh };
271 running_size += li.QuadPart;
272 #else
273 running_size += info.stat.st_size;
274 #endif
276 return running_size;
279 ///////////////////////////////////////////////
280 // FileEnumerator
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_));
291 } // namespace