hfile.h 2.2 KB

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