hfile.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. if (filesize == 0) return 0;
  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. if (filesize == 0) return 0;
  65. str.resize(filesize);
  66. return fread((void*)str.data(), 1, filesize, fp);
  67. }
  68. bool readline(std::string& str) {
  69. str.clear();
  70. char ch;
  71. while (fread(&ch, 1, 1, fp)) {
  72. if (ch == '\n') {
  73. // unix: LF
  74. return true;
  75. }
  76. if (ch == '\r') {
  77. // dos: CRLF
  78. // read LF
  79. if (fread(&ch, 1, 1, fp) && ch != '\n') {
  80. // mac: CR
  81. fseek(fp, -1, SEEK_CUR);
  82. }
  83. return true;
  84. }
  85. str += ch;
  86. }
  87. return str.length() != 0;
  88. }
  89. int readrange(std::string& str, size_t from = 0, size_t to = 0) {
  90. size_t filesize = size();
  91. if (filesize == 0) return 0;
  92. if (to == 0 || to >= filesize) to = filesize - 1;
  93. size_t readbytes = to - from + 1;
  94. str.resize(readbytes);
  95. fseek(fp, from, SEEK_SET);
  96. return fread((void*)str.data(), 1, readbytes, fp);
  97. }
  98. public:
  99. char filepath[MAX_PATH];
  100. FILE* fp;
  101. };
  102. #endif // HV_FILE_H_