hfile.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 "hdef.h"
  9. #include "hbuf.h"
  10. #include "herr.h"
  11. #include "hstring.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_t& buf) {
  44. size_t filesize = size();
  45. buf.init(filesize);
  46. return fread(buf.base, 1, buf.len, _fp);
  47. }
  48. size_t readall(string& str) {
  49. size_t filesize = size();
  50. str.resize(filesize);
  51. return fread((void*)str.data(), 1, filesize, _fp);
  52. }
  53. bool readline(string& str) {
  54. str.clear();
  55. char ch;
  56. while (fread(&ch, 1, 1, _fp)) {
  57. if (ch == '\n') {
  58. return true;
  59. }
  60. str += ch;
  61. }
  62. return str.length() != 0;
  63. }
  64. size_t write(const void* ptr, size_t len) {
  65. return fwrite(ptr, 1, len, _fp);
  66. }
  67. char _filepath[MAX_PATH];
  68. FILE* _fp;
  69. };
  70. #endif // HW_FILE_H_