hfile.h 2.6 KB

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