read.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 source tree.
  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. for (;;) {
  14. n = read(fd, buf, count);
  15. if (n >= 0 || errno != EINTR)
  16. break;
  17. /* Some callers set errno=0, are upset when they see EINTR.
  18. * Returning EINTR is wrong since we retry read(),
  19. * the "error" was transient.
  20. */
  21. errno = 0;
  22. /* repeat the read() */
  23. }
  24. return n;
  25. }
  26. /*
  27. * Read all of the supplied buffer from a file.
  28. * This does multiple reads as necessary.
  29. * Returns the amount read, or -1 on an error.
  30. * A short read is returned on an end of file.
  31. */
  32. ssize_t FAST_FUNC full_read(int fd, void *buf, size_t len)
  33. {
  34. ssize_t cc;
  35. ssize_t total;
  36. total = 0;
  37. while (len) {
  38. cc = safe_read(fd, buf, len);
  39. if (cc < 0) {
  40. if (total) {
  41. /* we already have some! */
  42. /* user can do another read to know the error code */
  43. return total;
  44. }
  45. return cc; /* read() returns -1 on failure. */
  46. }
  47. if (cc == 0)
  48. break;
  49. buf = ((char *)buf) + cc;
  50. total += cc;
  51. len -= cc;
  52. }
  53. return total;
  54. }
  55. ssize_t FAST_FUNC read_close(int fd, void *buf, size_t size)
  56. {
  57. /*int e;*/
  58. size = full_read(fd, buf, size);
  59. /*e = errno;*/
  60. close(fd);
  61. /*errno = e;*/
  62. return size;
  63. }
  64. ssize_t FAST_FUNC open_read_close(const char *filename, void *buf, size_t size)
  65. {
  66. int fd = open(filename, O_RDONLY);
  67. if (fd < 0)
  68. return fd;
  69. return read_close(fd, buf, size);
  70. }