hfile.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. size_t read(void* ptr, size_t len) {
  28. return fread(ptr, 1, len, fp);
  29. }
  30. size_t write(const void* ptr, size_t len) {
  31. return fwrite(ptr, 1, len, fp);
  32. }
  33. size_t size() {
  34. struct stat st;
  35. memset(&st, 0, sizeof(st));
  36. stat(filepath, &st);
  37. return st.st_size;
  38. }
  39. size_t readall(HBuf& buf) {
  40. size_t filesize = size();
  41. buf.resize(filesize);
  42. return fread(buf.base, 1, filesize, fp);
  43. }
  44. size_t readall(std::string& str) {
  45. size_t filesize = size();
  46. str.resize(filesize);
  47. return fread((void*)str.data(), 1, filesize, fp);
  48. }
  49. bool readline(std::string& str) {
  50. str.clear();
  51. char ch;
  52. while (fread(&ch, 1, 1, fp)) {
  53. if (ch == LF) {
  54. // unix: LF
  55. return true;
  56. }
  57. if (ch == CR) {
  58. // dos: CRLF
  59. // read LF
  60. if (fread(&ch, 1, 1, fp) && ch != LF) {
  61. // mac: CR
  62. fseek(fp, -1, SEEK_CUR);
  63. }
  64. return true;
  65. }
  66. str += ch;
  67. }
  68. return str.length() != 0;
  69. }
  70. public:
  71. char filepath[MAX_PATH];
  72. FILE* fp;
  73. };
  74. #endif // HV_FILE_H_