hfile.h 1.9 KB

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