1 /*
2 * Copyright (c) 2022 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 static bool FileExists(BASE_NS::string_view path);
43
44 // Close file.
45 void Close() override;
46
47 uint64_t Read(void* buffer, uint64_t count) override;
48
49 uint64_t Write(const void* buffer, uint64_t count) override;
50
51 uint64_t Append(const void* buffer, uint64_t count, uint64_t flushSize) override;
52
53 uint64_t GetLength() const override;
54
55 bool Seek(uint64_t offset) override;
56
57 uint64_t GetPosition() const override;
58
59 protected:
60 void Destroy() override
61 {
62 delete this;
63 }
64
65 private:
66 bool IsValidPath(const BASE_NS::string_view path);
67
68 Mode mode_ { Mode::INVALID };
69 mutable std::fstream file_;
70 };
71 CORE_END_NAMESPACE()
72
73 #endif // CORE_IO_STD_FILE_H
74