Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include "stdafx.h"
  4.  
  5. #include <memory>
  6. #include <string>
  7. #include <stdio.h>
  8. #include <vector>
  9.  
  10. class CFile
  11. {
  12. private:
  13. std::unique_ptr<FILE> uFile;
  14. bool opened;
  15.  
  16. void close();
  17.  
  18. public:
  19.  
  20. CFile() : opened(false) {};
  21. CFile operator=(const CFile&) = delete;
  22. CFile(const CFile&) = delete;
  23.  
  24. void open(const std::string name, const std::string mode);
  25.  
  26. // writing
  27. template <typename T, size_t N> // array
  28. void write(const T (&arr)[N]);
  29.  
  30. template <typename T>
  31. void write(const T & element); // single element
  32.  
  33. // reading
  34. template <typename T, size_t N> // array
  35. void read(T* arr);
  36.  
  37. template <typename T>
  38. T read(); // single element
  39.  
  40. ~CFile();
  41. };
  42.  
  43. template<typename T, size_t N>
  44. void CFile::write(const T(&arr)[N])
  45. {
  46. if (!opened)
  47. {
  48. throw std::exception("File has not been opened");
  49. }
  50.  
  51. fwrite(arr, sizeof(T), N, uFile.get());
  52. if (ferror(uFile.get()))
  53. {
  54. throw std::exception("Writing array of elements to file failed");
  55. }
  56. }
  57.  
  58. template<typename T>
  59. void CFile::write(const T & element)
  60. {
  61. if (!opened)
  62. {
  63. throw std::exception("File has not been opened");
  64. }
  65.  
  66. fwrite(&element, sizeof(element), 1, uFile.get());
  67. if (ferror(uFile.get()))
  68. {
  69. throw std::exception("Writing element to file failed");
  70. }
  71. }
  72.  
  73. template<typename T, size_t N>
  74. void CFile::read(T* arr)
  75. {
  76. if (!opened)
  77. {
  78. throw std::exception("File has not been opened");
  79. }
  80.  
  81. fread(arr, sizeof(T), N, uFile.get());
  82. if (ferror(uFile.get()))
  83. {
  84. throw std::exception("Reading array of elements from file failed");
  85. }
  86. }
  87.  
  88. template<typename T>
  89. T CFile::read()
  90. {
  91. if (!opened)
  92. {
  93. throw std::exception("File has not been opened");
  94. }
  95.  
  96. T element;
  97. fread(&element, sizeof(T), 1, uFile.get());
  98. if (ferror(uFile.get()))
  99. {
  100. throw std::exception("Reading element from file failed");
  101. }
  102. return element;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement