TextReader.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include "Types.h"
  24. namespace crown
  25. {
  26. class File;
  27. /// A reader that offers a convenient way to read text from a File
  28. class TextReader
  29. {
  30. public:
  31. //-----------------------------------------------------------------------------
  32. TextReader(File& file) : m_file(file)
  33. {
  34. }
  35. /// Reads characters from file and stores them as a C string
  36. /// into string until (size-1) characters have been read or
  37. /// either a newline or the End-of-File is reached, whichever
  38. /// comes first.
  39. /// A newline character makes fgets stop reading, but it is considered
  40. /// a valid character and therefore it is included in the string copied to string.
  41. /// A null character is automatically appended in str after the characters read to
  42. /// signal the end of the C string.
  43. size_t read_string(char* string, size_t size)
  44. {
  45. char current_char;
  46. size_t bytes_read = 0;
  47. while(!m_file.end_of_file() && bytes_read < size - 1)
  48. {
  49. m_file.read(&current_char, 1);
  50. string[bytes_read] = current_char;
  51. bytes_read++;
  52. if (current_char == '\n')
  53. {
  54. break;
  55. }
  56. }
  57. string[bytes_read] = '\0';
  58. return bytes_read;
  59. }
  60. private:
  61. File& m_file;
  62. };
  63. } // namespace crown