read.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. */
  9. #include "libbb.h"
  10. ssize_t FAST_FUNC safe_read(int fd, void *buf, size_t count)
  11. {
  12. ssize_t n;
  13. do {
  14. n = read(fd, buf, count);
  15. } while (n < 0 && errno == EINTR);
  16. return n;
  17. }
  18. /*
  19. * Read all of the supplied buffer from a file.
  20. * This does multiple reads as necessary.
  21. * Returns the amount read, or -1 on an error.
  22. * A short read is returned on an end of file.
  23. */
  24. ssize_t FAST_FUNC full_read(int fd, void *buf, size_t len)
  25. {
  26. ssize_t cc;
  27. ssize_t total;
  28. total = 0;
  29. while (len) {
  30. cc = safe_read(fd, buf, len);
  31. if (cc < 0) {
  32. if (total) {
  33. /* we already have some! */
  34. /* user can do another read to know the error code */
  35. return total;
  36. }
  37. return cc; /* read() returns -1 on failure. */
  38. }
  39. if (cc == 0)
  40. break;
  41. buf = ((char *)buf) + cc;
  42. total += cc;
  43. len -= cc;
  44. }
  45. return total;
  46. }
  47. ssize_t FAST_FUNC read_close(int fd, void *buf, size_t size)
  48. {
  49. /*int e;*/
  50. size = full_read(fd, buf, size);
  51. /*e = errno;*/
  52. close(fd);
  53. /*errno = e;*/
  54. return size;
  55. }
  56. ssize_t FAST_FUNC open_read_close(const char *filename, void *buf, size_t size)
  57. {
  58. int fd = open(filename, O_RDONLY);
  59. if (fd < 0)
  60. return fd;
  61. return read_close(fd, buf, size);
  62. }