ES-2024 reverter
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.4KB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include "filedata.h"
  8. struct filedata * get_filedata(const char *filename)
  9. {
  10. int fd = open(filename, O_RDONLY);
  11. if (fd < 0) {
  12. perror("get_filedata(): open()");
  13. return NULL;
  14. }
  15. struct stat filestat;
  16. if (fstat(fd, &filestat) < 0) {
  17. perror("get_filedata(): fstat()");
  18. close(fd);
  19. return NULL;
  20. }
  21. struct filedata *filedata = malloc(sizeof(struct filedata) + filestat.st_size);
  22. if (filedata == NULL) {
  23. perror("get_filedata(): malloc()");
  24. close(fd);
  25. return NULL;
  26. }
  27. filedata->size = filestat.st_size;
  28. int readsize = read(fd, filedata->data, filedata->size);
  29. if (readsize != filedata->size) {
  30. perror("get_filedata(): read()");
  31. free(filedata);
  32. close(fd);
  33. return NULL;
  34. }
  35. close(fd);
  36. return filedata;
  37. }
  38. struct filedata * alloc_filedata(int size)
  39. {
  40. struct filedata *retval = malloc(sizeof(struct filedata) + size);
  41. if (retval == NULL) {
  42. perror("alloc_filedata(): malloc()");
  43. return NULL;
  44. }
  45. retval->size = size;
  46. return retval;
  47. }
  48. int put_filedata(const char *filename, struct filedata *filedata)
  49. {
  50. int fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0644);
  51. if (fd < 0) {
  52. perror("put_filedata(): open()");
  53. return -1;
  54. }
  55. int writesize = write(fd, filedata->data, filedata->size);
  56. if (writesize != filedata->size) {
  57. perror("put_filedata(): write()");
  58. close(fd);
  59. return -1;
  60. }
  61. close(fd);
  62. return 0;
  63. }