filestream.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2011 Milo Yip
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #ifndef RAPIDJSON_FILESTREAM_H_
  21. #define RAPIDJSON_FILESTREAM_H_
  22. #include "rapidjson.h"
  23. #include <cstdio>
  24. RAPIDJSON_NAMESPACE_BEGIN
  25. //! (Deprecated) Wrapper of C file stream for input or output.
  26. /*!
  27. This simple wrapper does not check the validity of the stream.
  28. \note implements Stream concept
  29. \note deprecated: This was only for basic testing in version 0.1, it is found that the performance is very low by using fgetc(). Use FileReadStream instead.
  30. */
  31. class FileStream {
  32. public:
  33. typedef char Ch; //!< Character type. Only support char.
  34. FileStream(std::FILE* fp) : fp_(fp), current_('\0'), count_(0) { Read(); }
  35. char Peek() const { return current_; }
  36. char Take() { char c = current_; Read(); return c; }
  37. size_t Tell() const { return count_; }
  38. void Put(char c) { fputc(c, fp_); }
  39. void Flush() { fflush(fp_); }
  40. // Not implemented
  41. char* PutBegin() { return 0; }
  42. size_t PutEnd(char*) { return 0; }
  43. private:
  44. // Prohibit copy constructor & assignment operator.
  45. FileStream(const FileStream&);
  46. FileStream& operator=(const FileStream&);
  47. void Read() {
  48. RAPIDJSON_ASSERT(fp_ != 0);
  49. int c = fgetc(fp_);
  50. if (c != EOF) {
  51. current_ = (char)c;
  52. count_++;
  53. }
  54. else if (current_ != '\0')
  55. current_ = '\0';
  56. }
  57. std::FILE* fp_;
  58. char current_;
  59. size_t count_;
  60. };
  61. RAPIDJSON_NAMESPACE_END
  62. #endif // RAPIDJSON_FILESTREAM_H_