SkSLFileOutputStream.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 2017 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #ifndef SKSL_FILEOUTPUTSTREAM
  8. #define SKSL_FILEOUTPUTSTREAM
  9. #include "src/sksl/SkSLOutputStream.h"
  10. #include "src/sksl/SkSLUtil.h"
  11. #include <stdio.h>
  12. namespace SkSL {
  13. class FileOutputStream : public OutputStream {
  14. public:
  15. FileOutputStream(const char* name) {
  16. fFile = fopen(name, "wb");
  17. }
  18. ~FileOutputStream() override {
  19. SkASSERT(!fOpen);
  20. }
  21. bool isValid() const override {
  22. return nullptr != fFile;
  23. }
  24. void write8(uint8_t b) override {
  25. SkASSERT(fOpen);
  26. if (isValid()) {
  27. if (EOF == fputc(b, fFile)) {
  28. fFile = nullptr;
  29. }
  30. }
  31. }
  32. void writeText(const char* s) override {
  33. SkASSERT(fOpen);
  34. if (isValid()) {
  35. if (EOF == fputs(s, fFile)) {
  36. fFile = nullptr;
  37. }
  38. }
  39. }
  40. void write(const void* s, size_t size) override {
  41. if (isValid()) {
  42. size_t written = fwrite(s, 1, size, fFile);
  43. if (written != size) {
  44. fFile = nullptr;
  45. }
  46. }
  47. }
  48. bool close() {
  49. fOpen = false;
  50. if (isValid() && fclose(fFile)) {
  51. fFile = nullptr;
  52. return false;
  53. }
  54. return true;
  55. }
  56. private:
  57. bool fOpen = true;
  58. FILE *fFile;
  59. typedef OutputStream INHERITED;
  60. };
  61. } // namespace
  62. #endif