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 : #include "base/file_util.h"
6 :
7 : #include <fcntl.h>
8 : #if defined(ANDROID) || defined(OS_POSIX)
9 : #include <unistd.h>
10 : #endif
11 :
12 : #include <string>
13 : #include <vector>
14 :
15 : #include "base/eintr_wrapper.h"
16 : #include "base/file_path.h"
17 : #include "base/string_util.h"
18 :
19 : namespace file_util {
20 :
21 0 : bool GetTempDir(FilePath* path) {
22 0 : const char* tmp = getenv("TMPDIR");
23 0 : if (tmp)
24 0 : *path = FilePath(tmp);
25 : else
26 0 : *path = FilePath("/tmp");
27 0 : return true;
28 : }
29 :
30 0 : bool GetShmemTempDir(FilePath* path) {
31 : #ifdef ANDROID
32 : return GetTempDir(path);
33 : #else
34 0 : *path = FilePath("/dev/shm");
35 0 : return true;
36 : #endif
37 : }
38 :
39 0 : bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
40 0 : int infile = open(from_path.value().c_str(), O_RDONLY);
41 0 : if (infile < 0)
42 0 : return false;
43 :
44 0 : int outfile = creat(to_path.value().c_str(), 0666);
45 0 : if (outfile < 0) {
46 0 : close(infile);
47 0 : return false;
48 : }
49 :
50 0 : const size_t kBufferSize = 32768;
51 0 : std::vector<char> buffer(kBufferSize);
52 0 : bool result = true;
53 :
54 0 : while (result) {
55 0 : ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
56 0 : if (bytes_read < 0) {
57 0 : result = false;
58 0 : break;
59 : }
60 0 : if (bytes_read == 0)
61 0 : break;
62 : // Allow for partial writes
63 0 : ssize_t bytes_written_per_read = 0;
64 0 : do {
65 0 : ssize_t bytes_written_partial = HANDLE_EINTR(write(
66 : outfile,
67 : &buffer[bytes_written_per_read],
68 : bytes_read - bytes_written_per_read));
69 0 : if (bytes_written_partial < 0) {
70 0 : result = false;
71 0 : break;
72 : }
73 0 : bytes_written_per_read += bytes_written_partial;
74 : } while (bytes_written_per_read < bytes_read);
75 : }
76 :
77 0 : if (HANDLE_EINTR(close(infile)) < 0)
78 0 : result = false;
79 0 : if (HANDLE_EINTR(close(outfile)) < 0)
80 0 : result = false;
81 :
82 0 : return result;
83 : }
84 :
85 : } // namespace file_util
|