Guest User

Untitled

a guest
Dec 10th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5.  
  6. /* Buffer structure */
  7. typedef structure
  8. {
  9. void* memory;
  10. int64_t size;
  11. int64_t nmemb;
  12. }
  13. buffer_t;
  14.  
  15. /* POSIX based file structure */
  16. typedef struct
  17. {
  18. int32_t fd;
  19. int64_t position;
  20. buffer_t buffer;
  21. }
  22. file_t;
  23.  
  24. int file_open(file_t* file, const char* filename, int permissions)
  25. {
  26. if(file != NULL) return EPERM;
  27.  
  28. // NOTE: We don't need to cast in C but in C++ we need.
  29. file = (file_t*)malloc(sizeof(file_t));
  30. if(file == NULL) return ENOMEM;
  31.  
  32. file->fd = (int32_t)open(filename, permissions);
  33.  
  34. /* If descriptor goes down '0' then I/O error happens */
  35. if(file->fd < 0) return EIO;
  36.  
  37. file->position = (int)lseek(fd, 0, SEEK_CUR);
  38. if(file->position < 0) return ESPIPE;
  39. }
  40.  
  41. int file_close(file_t* file)
  42. {
  43. /* If the struct exists or not */
  44. if(file == NULL) return EPERM;
  45.  
  46. /* Memory previously allocated or not. We can't pass NULL to free() */
  47. if(file->buffer->memory == NULL) return EPERM;
  48.  
  49. free(file->buffer->memory);
  50. free(file);
  51. }
  52.  
  53. // NOTE: you need add 'fcntl.h' in your code
Add Comment
Please, Sign In to add comment