file_wrapper_input.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2012, The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <sys/stat.h>
  17. #include <stdlib.h>
  18. #include "bcinfo/Wrap/file_wrapper_input.h"
  19. FileWrapperInput::FileWrapperInput(const char* name) :
  20. _name(name), _at_eof(false), _size_found(false), _size(0) {
  21. _file = fopen(name, "rb");
  22. if (_file == nullptr) {
  23. fprintf(stderr, "Unable to open: %s\n", name);
  24. exit(1);
  25. }
  26. }
  27. FileWrapperInput::~FileWrapperInput() {
  28. fclose(_file);
  29. }
  30. size_t FileWrapperInput::Read(uint8_t* buffer, size_t wanted) {
  31. size_t found = fread((char*) buffer, 1, wanted, _file);
  32. if (feof(_file) || ferror(_file)) {
  33. _at_eof = true;
  34. }
  35. return found;
  36. }
  37. bool FileWrapperInput::AtEof() {
  38. return _at_eof;
  39. }
  40. off_t FileWrapperInput::Size() {
  41. if (_size_found) return _size;
  42. struct stat st;
  43. if (stat(_name, &st) == 0) {
  44. _size_found = true;
  45. _size = st.st_size;
  46. return _size;
  47. } else {
  48. fprintf(stderr, "Unable to compute file size: %s\n", _name);
  49. exit(1);
  50. }
  51. // NOT REACHABLE.
  52. return 0;
  53. }
  54. bool FileWrapperInput::Seek(uint32_t pos) {
  55. return fseek(_file, (long) pos, SEEK_SET) == 0; // NOLINT
  56. }