1 // Copyright 2021 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://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, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <fstream> 17 18 #include "pw_stream/stream.h" 19 20 namespace pw::stream { 21 22 // Wraps an std::ifstream with the Reader interface. 23 class StdFileReader final : public stream::SeekableReader { 24 public: StdFileReader(const char * path)25 StdFileReader(const char* path) : stream_(path, std::ios::binary) {} 26 Close()27 void Close() { stream_.close(); } 28 29 private: 30 StatusWithSize DoRead(ByteSpan dest) override; 31 Status DoSeek(ptrdiff_t offset, Whence origin) override; 32 33 std::ifstream stream_; 34 }; 35 36 // Wraps an std::ofstream with the Writer interface. 37 class StdFileWriter final : public stream::SeekableWriter { 38 public: StdFileWriter(const char * path)39 StdFileWriter(const char* path) 40 : stream_(path, std::ios::binary | std::ios::trunc) {} 41 Close()42 void Close() { stream_.close(); } 43 44 private: 45 Status DoWrite(ConstByteSpan data) override; 46 Status DoSeek(ptrdiff_t offset, Whence origin) override; 47 48 std::ofstream stream_; 49 }; 50 51 } // namespace pw::stream 52