hfile.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. static size_t size(const char* filepath) {
  37. struct stat st;
  38. memset(&st, 0, sizeof(st));
  39. stat(filepath, &st);
  40. return st.st_size;
  41. }
  42. size_t size() {
  43. return HFile::size(filepath);
  44. }
  45. size_t readall(HBuf& buf) {
  46. size_t filesize = size();
  47. buf.resize(filesize);
  48. return fread(buf.base, 1, filesize, fp);
  49. }
  50. size_t readall(std::string& str) {
  51. size_t filesize = size();
  52. str.resize(filesize);
  53. return fread((void*)str.data(), 1, filesize, fp);
  54. }
  55. bool readline(std::string& str) {
  56. str.clear();
  57. char ch;
  58. while (fread(&ch, 1, 1, fp)) {
  59. if (ch == LF) {
  60. // unix: LF
  61. return true;
  62. }
  63. if (ch == CR) {
  64. // dos: CRLF
  65. // read LF
  66. if (fread(&ch, 1, 1, fp) && ch != LF) {
  67. // mac: CR
  68. fseek(fp, -1, SEEK_CUR);
  69. }
  70. return true;
  71. }
  72. str += ch;
  73. }
  74. return str.length() != 0;
  75. }
  76. int readrange(std::string& str, size_t from = 0, size_t to = 0) {
  77. size_t filesize = size();
  78. if (to == 0 || to >= filesize) to = filesize - 1;
  79. size_t readbytes = to - from + 1;
  80. str.resize(readbytes);
  81. fseek(fp, from, SEEK_SET);
  82. return fread((void*)str.data(), 1, readbytes, fp);
  83. }
  84. public:
  85. char filepath[MAX_PATH];
  86. FILE* fp;
  87. };
  88. #endif // HV_FILE_H_