hfile.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. class HFile {
  12. public:
  13. HFile() {
  14. _fp = NULL;
  15. }
  16. ~HFile() {
  17. close();
  18. }
  19. int open(const char* filepath, const char* mode) {
  20. close();
  21. strncpy(_filepath, filepath, MAX_PATH);
  22. _fp = fopen(filepath, mode);
  23. if (_fp == NULL) {
  24. return ERR_OPEN_FILE;
  25. }
  26. return 0;
  27. }
  28. void close() {
  29. if (_fp) {
  30. fclose(_fp);
  31. _fp = NULL;
  32. }
  33. }
  34. size_t size() {
  35. struct stat st;
  36. stat(_filepath, &st);
  37. return st.st_size;
  38. }
  39. size_t read(void* ptr, size_t len) {
  40. return fread(ptr, 1, len, _fp);
  41. }
  42. size_t readall(hbuf_t& buf) {
  43. size_t filesize = size();
  44. buf.init(filesize);
  45. return fread(buf.base, 1, buf.len, _fp);
  46. }
  47. bool readline(string& str) {
  48. str.clear();
  49. char ch;
  50. while (fread(&ch, 1, 1, _fp)) {
  51. if (ch == '\n') {
  52. return true;
  53. }
  54. str += ch;
  55. }
  56. return str.length() != 0;
  57. }
  58. size_t write(const void* ptr, size_t len) {
  59. return fwrite(ptr, 1, len, _fp);
  60. }
  61. char _filepath[MAX_PATH];
  62. FILE* _fp;
  63. };
  64. #endif // HW_FILE_H