hfile.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #ifndef HW_FILE_H_
  2. #define HW_FILE_H_
  3. #include <string>
  4. #include "hdef.h"
  5. #include "hbuf.h"
  6. #include "herr.h"
  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(_filepath, filepath, MAX_PATH);
  18. _fp = fopen(filepath, mode);
  19. if (_fp == NULL) {
  20. return ERR_OPEN_FILE;
  21. }
  22. return 0;
  23. }
  24. void close() {
  25. if (_fp) {
  26. fclose(_fp);
  27. _fp = NULL;
  28. }
  29. }
  30. size_t size() {
  31. struct stat st;
  32. stat(_filepath, &st);
  33. return st.st_size;
  34. }
  35. size_t read(void* ptr, size_t len) {
  36. return fread(ptr, 1, len, _fp);
  37. }
  38. size_t readall(HBuf& buf) {
  39. size_t filesize = size();
  40. buf.resize(filesize);
  41. return fread(buf.base, 1, filesize, _fp);
  42. }
  43. size_t readall(std::string& str) {
  44. size_t filesize = size();
  45. str.resize(filesize);
  46. return fread((void*)str.data(), 1, filesize, _fp);
  47. }
  48. bool readline(std::string& str) {
  49. str.clear();
  50. char ch;
  51. while (fread(&ch, 1, 1, _fp)) {
  52. if (ch == LF) {
  53. // unix: LF
  54. return true;
  55. }
  56. if (ch == CR) {
  57. // dos: CRLF
  58. // read LF
  59. if (fread(&ch, 1, 1, _fp) && ch != LF) {
  60. // mac: CR
  61. fseek(_fp, -1, SEEK_CUR);
  62. }
  63. return true;
  64. }
  65. str += ch;
  66. }
  67. return str.length() != 0;
  68. }
  69. size_t write(const void* ptr, size_t len) {
  70. return fwrite(ptr, 1, len, _fp);
  71. }
  72. char _filepath[MAX_PATH];
  73. FILE* _fp;
  74. };
  75. #endif // HW_FILE_H_