filemap.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "filemap.h"
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <sys/fcntl.h> /* open */
  5. #include <sys/mman.h> /* mmap */
  6. #include <unistd.h> /* close */
  7. #include <stdio.h> /* perror */
  8. struct AFileMap aFileMapOpen(const char *filename) {
  9. struct AFileMap ret;
  10. ret.map = 0;
  11. ret.size = 0;
  12. ret.impl_.fd = open(filename, O_RDONLY);
  13. if (ret.impl_.fd < 0) { perror("cannot open file"); goto exit; }
  14. struct stat stat;
  15. if (fstat(ret.impl_.fd, &stat) < 0) { perror("cannot fstat file"); goto exit; }
  16. ret.size = stat.st_size;
  17. ret.map = mmap(0, ret.size, PROT_READ, MAP_PRIVATE, ret.impl_.fd, 0);
  18. if (!ret.map) perror("cannot mmap file");
  19. exit:
  20. if (!ret.map && ret.impl_.fd > 0)
  21. close(ret.impl_.fd);
  22. return ret;
  23. }
  24. void aFileMapClose(struct AFileMap *file) {
  25. if (file->map && file->impl_.fd > 0) {
  26. munmap((void*)file->map, file->size);
  27. close(file->impl_.fd);
  28. }
  29. }
  30. void aFileReset(struct AFile *file) {
  31. file->size = 0;
  32. file->impl_.fd = -1;
  33. }
  34. enum AFileResult aFileOpen(struct AFile *file, const char *filename) {
  35. file->impl_.fd = open(filename, O_RDONLY);
  36. if (file->impl_.fd < 0)
  37. return AFile_Fail;
  38. struct stat stat;
  39. fstat(file->impl_.fd, &stat);
  40. file->size = stat.st_size;
  41. return AFile_Success;
  42. }
  43. size_t aFileRead(struct AFile *file, size_t size, void *buffer) {
  44. ssize_t rd = read(file->impl_.fd, buffer, size);
  45. if (rd < 0) perror("read(fd)");
  46. return rd;
  47. }
  48. size_t aFileReadAtOffset(struct AFile *file, size_t off, size_t size, void *buffer) {
  49. ssize_t rd = pread(file->impl_.fd, buffer, size, off);
  50. if (rd < 0) perror("pread(fd)");
  51. return rd;
  52. }
  53. void aFileClose(struct AFile *file) {
  54. if (file->impl_.fd > 0) {
  55. close(file->impl_.fd);
  56. aFileReset(file);
  57. }
  58. }