blob: 10fb69834b1e30f33f9707bd1a7b48e3378e224e [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#ifndef WEBRTC_BASE_FILE_H_
12#define WEBRTC_BASE_FILE_H_
13
14#include <stdint.h>
15
16#include <string>
17
18#include "webrtc/base/platform_file.h"
19#include "webrtc/base/constructormagic.h"
20
21namespace rtc {
22
23// This class wraps the platform specific APIs for simple file interactions.
24//
25// The various read and write methods are best effort, i.e. if an underlying
26// call does not manage to read/write all the data more calls will be performed,
27// until an error is detected or all data is read/written.
28class File {
29 public:
30 // Wraps the given PlatformFile. This class is then responsible for closing
31 // the file, which will be done in the destructor if Close is never called.
32 explicit File(PlatformFile);
Viktor Palmkvist1d477ea2016-10-03 13:16:02 +020033 // The default constructor produces a closed file.
34 File();
Viktor Palmkvist4ec6a0c2016-09-02 13:38:32 +020035 ~File();
36
37 File(File&& other);
38 File& operator=(File&& other);
39
Viktor Palmkvist971eb272016-09-16 10:19:23 +020040 // Open and Create give files with both reading and writing enabled.
Viktor Palmkvist4ec6a0c2016-09-02 13:38:32 +020041 static File Open(const std::string& path);
Viktor Palmkvist971eb272016-09-16 10:19:23 +020042 // If the file already exists it will be overwritten.
43 static File Create(const std::string& path);
Viktor Palmkvist4ec6a0c2016-09-02 13:38:32 +020044
45 size_t Write(const uint8_t* data, size_t length);
46 size_t Read(uint8_t* buffer, size_t length);
47
48 // The current position in the file after a call to these methods is platform
49 // dependent (MSVC gives position offset+length, most other
50 // compilers/platforms do not alter the position), i.e. do not depend on it,
51 // do a Seek before any subsequent Read/Write.
52 size_t WriteAt(const uint8_t* data, size_t length, size_t offset);
53 size_t ReadAt(uint8_t* buffer, size_t length, size_t offset);
54
55 // Attempt to position the file at the given offset from the start.
56 // Returns true if successful, false otherwise.
57 bool Seek(size_t offset);
58
59 // Attempt to close the file. Returns true if successful, false otherwise,
60 // most notably when the file is already closed.
61 bool Close();
62
63 bool IsOpen();
64
65 private:
66 PlatformFile file_;
67 RTC_DISALLOW_COPY_AND_ASSIGN(File);
68};
69
70} // namespace rtc
71
72#endif // WEBRTC_BASE_FILE_H_