file_utils.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // file_utils.c
  3. // electra
  4. //
  5. // Created by Jamie on 27/01/2018.
  6. // Copyright © 2018 Electra Team. All rights reserved.
  7. //
  8. #include "file_utils.h"
  9. #include <sys/stat.h>
  10. #include <sys/fcntl.h>
  11. #include <unistd.h>
  12. #include <errno.h>
  13. int file_exists_electra(const char *filename) {
  14. struct stat buffer;
  15. int r = stat(filename, &buffer);
  16. return (r == 0);
  17. }
  18. int cp_electra(const char *to, const char *from) {
  19. int fd_to, fd_from;
  20. char buf[4096];
  21. ssize_t nread;
  22. int saved_errno;
  23. fd_from = open(from, O_RDONLY);
  24. if (fd_from < 0)
  25. return -1;
  26. fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);
  27. if (fd_to < 0)
  28. goto out_error;
  29. while ((nread = read(fd_from, buf, sizeof buf)) > 0) {
  30. char *out_ptr = buf;
  31. ssize_t nwritten;
  32. do {
  33. nwritten = write(fd_to, out_ptr, nread);
  34. if (nwritten >= 0) {
  35. nread -= nwritten;
  36. out_ptr += nwritten;
  37. }
  38. else if (errno != EINTR) {
  39. goto out_error;
  40. }
  41. } while (nread > 0);
  42. }
  43. if (nread == 0)
  44. {
  45. if (close(fd_to) < 0)
  46. {
  47. fd_to = -1;
  48. goto out_error;
  49. }
  50. close(fd_from);
  51. /* Success! */
  52. return 0;
  53. }
  54. out_error:
  55. saved_errno = errno;
  56. close(fd_from);
  57. if (fd_to >= 0)
  58. close(fd_to);
  59. errno = saved_errno;
  60. return -1;
  61. }