You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileInStream.cxx 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright (C) 2013 D. R. Commander. All Rights Reserved.
  3. * Copyright 2015 Pierre Ossman for Cendio AB
  4. *
  5. * This is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This software is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this software; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  18. * USA.
  19. */
  20. #include <errno.h>
  21. #include <rdr/Exception.h>
  22. #include <rdr/FileInStream.h>
  23. using namespace rdr;
  24. FileInStream::FileInStream(const char *fileName)
  25. {
  26. file = fopen(fileName, "rb");
  27. if (!file)
  28. throw SystemException("fopen", errno);
  29. ptr = end = b;
  30. }
  31. FileInStream::~FileInStream(void) {
  32. if (file) {
  33. fclose(file);
  34. file = NULL;
  35. }
  36. }
  37. void FileInStream::reset(void) {
  38. if (!file)
  39. throw Exception("File is not open");
  40. if (fseek(file, 0, SEEK_SET) != 0)
  41. throw SystemException("fseek", errno);
  42. ptr = end = b;
  43. }
  44. int FileInStream::pos()
  45. {
  46. if (!file)
  47. throw Exception("File is not open");
  48. return ftell(file) + ptr - b;
  49. }
  50. int FileInStream::overrun(int itemSize, int nItems, bool wait)
  51. {
  52. if (itemSize > (int)sizeof(b))
  53. throw Exception("FileInStream overrun: max itemSize exceeded");
  54. if (end - ptr != 0)
  55. memmove(b, ptr, end - ptr);
  56. end -= ptr - b;
  57. ptr = b;
  58. while (end < b + itemSize) {
  59. size_t n = fread((U8 *)end, b + sizeof(b) - end, 1, file);
  60. if (n < 1) {
  61. if (n < 0 || ferror(file))
  62. throw SystemException("fread", errno);
  63. if (feof(file))
  64. throw EndOfStream();
  65. if (n == 0) { return 0; }
  66. }
  67. end += b + sizeof(b) - end;
  68. }
  69. if (itemSize * nItems > end - ptr)
  70. nItems = (end - ptr) / itemSize;
  71. return nItems;
  72. }