util.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #include "util.h"
  2. #include <sys/mman.h>
  3. int mkdir_p(char *path, mode_t mode)
  4. {
  5. struct stat st;
  6. int err;
  7. char *d = path;
  8. if (*d != '/')
  9. return -1;
  10. if (stat(path, &st) == 0)
  11. return 0;
  12. while (*++d == '/');
  13. while ((d = strchr(d, '/'))) {
  14. *d = '\0';
  15. err = stat(path, &st) && mkdir(path, mode);
  16. *d++ = '/';
  17. if (err)
  18. return -1;
  19. while (*d == '/')
  20. ++d;
  21. }
  22. return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
  23. }
  24. static int slow_copyfile(const char *from, const char *to)
  25. {
  26. int err = 0;
  27. char *line = NULL;
  28. size_t n;
  29. FILE *from_fp = fopen(from, "r"), *to_fp;
  30. if (from_fp == NULL)
  31. goto out;
  32. to_fp = fopen(to, "w");
  33. if (to_fp == NULL)
  34. goto out_fclose_from;
  35. while (getline(&line, &n, from_fp) > 0)
  36. if (fputs(line, to_fp) == EOF)
  37. goto out_fclose_to;
  38. err = 0;
  39. out_fclose_to:
  40. fclose(to_fp);
  41. free(line);
  42. out_fclose_from:
  43. fclose(from_fp);
  44. out:
  45. return err;
  46. }
  47. int copyfile(const char *from, const char *to)
  48. {
  49. int fromfd, tofd;
  50. struct stat st;
  51. void *addr;
  52. int err = -1;
  53. if (stat(from, &st))
  54. goto out;
  55. if (st.st_size == 0) /* /proc? do it slowly... */
  56. return slow_copyfile(from, to);
  57. fromfd = open(from, O_RDONLY);
  58. if (fromfd < 0)
  59. goto out;
  60. tofd = creat(to, 0755);
  61. if (tofd < 0)
  62. goto out_close_from;
  63. addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fromfd, 0);
  64. if (addr == MAP_FAILED)
  65. goto out_close_to;
  66. if (write(tofd, addr, st.st_size) == st.st_size)
  67. err = 0;
  68. munmap(addr, st.st_size);
  69. out_close_to:
  70. close(tofd);
  71. if (err)
  72. unlink(to);
  73. out_close_from:
  74. close(fromfd);
  75. out:
  76. return err;
  77. }
  78. unsigned long convert_unit(unsigned long value, char *unit)
  79. {
  80. *unit = ' ';
  81. if (value > 1000) {
  82. value /= 1000;
  83. *unit = 'K';
  84. }
  85. if (value > 1000) {
  86. value /= 1000;
  87. *unit = 'M';
  88. }
  89. if (value > 1000) {
  90. value /= 1000;
  91. *unit = 'G';
  92. }
  93. return value;
  94. }
  95. int readn(int fd, void *buf, size_t n)
  96. {
  97. void *buf_start = buf;
  98. while (n) {
  99. int ret = read(fd, buf, n);
  100. if (ret <= 0)
  101. return ret;
  102. n -= ret;
  103. buf += ret;
  104. }
  105. return buf - buf_start;
  106. }