1
0

hfile.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. #ifndef HV_FILE_H_
  2. #define HV_FILE_H_
  3. #include <string> // for std::string
  4. #include "hplatform.h" // for stat
  5. #include "hdef.h" // for LF, CR
  6. #include "hbuf.h" // for HBuf
  7. class HFile {
  8. public:
  9. HFile() {
  10. fp = NULL;
  11. }
  12. ~HFile() {
  13. close();
  14. }
  15. int open(const char* filepath, const char* mode) {
  16. close();
  17. strncpy(this->filepath, filepath, MAX_PATH);
  18. fp = fopen(filepath, mode);
  19. return fp ? 0 : errno;
  20. }
  21. void close() {
  22. if (fp) {
  23. fclose(fp);
  24. fp = NULL;
  25. }
  26. }
  27. bool isopen() {
  28. return fp != NULL;
  29. }
  30. size_t read(void* ptr, size_t len) {
  31. return fread(ptr, 1, len, fp);
  32. }
  33. size_t write(const void* ptr, size_t len) {
  34. return fwrite(ptr, 1, len, fp);
  35. }
  36. size_t write(const std::string& str) {
  37. return write(str.c_str(), str.length());
  38. }
  39. int seek(size_t offset, int whence = SEEK_SET) {
  40. return fseek(fp, offset, whence);
  41. }
  42. int tell() {
  43. return ftell(fp);
  44. }
  45. int flush() {
  46. return fflush(fp);
  47. }
  48. static size_t size(const char* filepath) {
  49. struct stat st;
  50. memset(&st, 0, sizeof(st));
  51. stat(filepath, &st);
  52. return st.st_size;
  53. }
  54. size_t size() {
  55. return HFile::size(filepath);
  56. }
  57. size_t readall(HBuf& buf) {
  58. size_t filesize = size();
  59. buf.resize(filesize);
  60. return fread(buf.base, 1, filesize, fp);
  61. }
  62. size_t readall(std::string& str) {
  63. size_t filesize = size();
  64. str.resize(filesize);
  65. return fread((void*)str.data(), 1, filesize, fp);
  66. }
  67. bool readline(std::string& str) {
  68. str.clear();
  69. char ch;
  70. while (fread(&ch, 1, 1, fp)) {
  71. if (ch == LF) {
  72. // unix: LF
  73. return true;
  74. }
  75. if (ch == CR) {
  76. // dos: CRLF
  77. // read LF
  78. if (fread(&ch, 1, 1, fp) && ch != LF) {
  79. // mac: CR
  80. fseek(fp, -1, SEEK_CUR);
  81. }
  82. return true;
  83. }
  84. str += ch;
  85. }
  86. return str.length() != 0;
  87. }
  88. int readrange(std::string& str, size_t from = 0, size_t to = 0) {
  89. size_t filesize = size();
  90. if (to == 0 || to >= filesize) to = filesize - 1;
  91. size_t readbytes = to - from + 1;
  92. str.resize(readbytes);
  93. fseek(fp, from, SEEK_SET);
  94. return fread((void*)str.data(), 1, readbytes, fp);
  95. }
  96. public:
  97. char filepath[MAX_PATH];
  98. FILE* fp;
  99. };
  100. #endif // HV_FILE_H_