blob: 2dde7938c2ca2c281366ef2bb4aba160edd56012 [file] [log] [blame]
Viktor Palmkvist4ec6a0c2016-09-02 13:38:32 +02001/*
2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/base/file.h"
12
13#include <errno.h>
14#include <fcntl.h>
15#include <sys/stat.h>
16#include <sys/types.h>
17#include <unistd.h>
18
19#include <limits>
20
21#include "webrtc/base/checks.h"
22
23namespace rtc {
24
25File File::Open(const std::string& path) {
26 return File(::open(path.c_str(), O_RDWR));
27}
28
29size_t File::Write(const uint8_t* data, size_t length) {
30 size_t total_written = 0;
31 do {
32 ssize_t written;
33 do {
34 written = ::write(file_, data + total_written, length - total_written);
35 } while (written == -1 && errno == EINTR);
36 if (written == -1)
37 break;
38 total_written += written;
39 } while (total_written < length);
40 return total_written;
41}
42
43size_t File::Read(uint8_t* buffer, size_t length) {
44 size_t total_read = 0;
45 do {
46 ssize_t read;
47 do {
48 read = ::read(file_, buffer + total_read, length - total_read);
49 } while (read == -1 && errno == EINTR);
50 if (read == -1)
51 break;
52 total_read += read;
53 } while (total_read < length);
54 return total_read;
55}
56
57size_t File::WriteAt(const uint8_t* data, size_t length, size_t offset) {
58 size_t total_written = 0;
59 do {
60 ssize_t written;
61 do {
62 written = ::pwrite(file_, data + total_written, length - total_written,
63 offset + total_written);
64 } while (written == -1 && errno == EINTR);
65 if (written == -1)
66 break;
67 total_written += written;
68 } while (total_written < length);
69 return total_written;
70}
71
72size_t File::ReadAt(uint8_t* buffer, size_t length, size_t offset) {
73 size_t total_read = 0;
74 do {
75 ssize_t read;
76 do {
77 read = ::pread(file_, buffer + total_read, length - total_read,
78 offset + total_read);
79 } while (read == -1 && errno == EINTR);
80 if (read == -1)
81 break;
82 total_read += read;
83 } while (total_read < length);
84 return total_read;
85}
86
87bool File::Seek(size_t offset) {
88 RTC_DCHECK_LE(offset, static_cast<size_t>(std::numeric_limits<off_t>::max()));
89 return lseek(file_, static_cast<off_t>(offset), SEEK_SET) != -1;
90}
91
92bool File::Close() {
93 if (file_ == rtc::kInvalidPlatformFileValue)
94 return false;
95 bool ret = close(file_) == 0;
96 file_ = rtc::kInvalidPlatformFileValue;
97 return ret;
98}
99
100} // namespace rtc