1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef CORE__IO__STD_FILE_H
17 #define CORE__IO__STD_FILE_H
18
19 #include <fstream>
20
21 #include <base/containers/string_view.h>
22 #include <core/io/intf_file.h>
23 #include <core/namespace.h>
24
CORE_BEGIN_NAMESPACE()25 CORE_BEGIN_NAMESPACE()
26 /** File system file.
27 * IFile implementation that wraps standard FILE handle and operations around it.
28 */
29 class StdFile final : public IFile {
30 public:
31 StdFile(Mode mode, std::fstream&& stream);
32 ~StdFile() override;
33
34 Mode GetMode() const override;
35
36 // Open an existing file, fails if the file does not exist.
37 static IFile::Ptr Open(BASE_NS::string_view path, Mode mode);
38
39 // Create a new file, the existing file will be overridden.
40 static IFile::Ptr Create(BASE_NS::string_view path, Mode mode);
41
42 // Close file.
43 void Close() override;
44
45 uint64_t Read(void* buffer, uint64_t count) override;
46
47 uint64_t Write(const void* buffer, uint64_t count) override;
48
49 uint64_t GetLength() const override;
50
51 bool Seek(uint64_t offset) override;
52
53 uint64_t GetPosition() const override;
54
55 protected:
56 void Destroy() override
57 {
58 delete this;
59 }
60
61 private:
62 bool IsValidPath(const BASE_NS::string_view path);
63
64 Mode mode_ { Mode::INVALID };
65 mutable std::fstream file_;
66 };
67 CORE_END_NAMESPACE()
68
69 #endif // CORE__IO__STD_FILE_H
70