full-write.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* An interface to read and write that retries (if necessary) until complete.
  2. Copyright (C) 1993, 1994, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
  3. 2004, 2005, 2006 Free Software Foundation, Inc.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software Foundation,
  14. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  15. #include <config.h>
  16. /* Specification. */
  17. #ifdef FULL_READ
  18. # include "full-read.h"
  19. #else
  20. # include "full-write.h"
  21. #endif
  22. #include <errno.h>
  23. #ifdef FULL_READ
  24. # include "safe-read.h"
  25. # define safe_rw safe_read
  26. # define full_rw full_read
  27. # undef const
  28. # define const /* empty */
  29. #else
  30. # include "safe-write.h"
  31. # define safe_rw safe_write
  32. # define full_rw full_write
  33. #endif
  34. #ifdef FULL_READ
  35. /* Set errno to zero upon EOF. */
  36. # define ZERO_BYTE_TRANSFER_ERRNO 0
  37. #else
  38. /* Some buggy drivers return 0 when one tries to write beyond
  39. a device's end. (Example: Linux 1.2.13 on /dev/fd0.)
  40. Set errno to ENOSPC so they get a sensible diagnostic. */
  41. # define ZERO_BYTE_TRANSFER_ERRNO ENOSPC
  42. #endif
  43. /* Write(read) COUNT bytes at BUF to(from) descriptor FD, retrying if
  44. interrupted or if a partial write(read) occurs. Return the number
  45. of bytes transferred.
  46. When writing, set errno if fewer than COUNT bytes are written.
  47. When reading, if fewer than COUNT bytes are read, you must examine
  48. errno to distinguish failure from EOF (errno == 0). */
  49. size_t
  50. full_rw (int fd, const void *buf, size_t count)
  51. {
  52. size_t total = 0;
  53. const char *ptr = (const char *) buf;
  54. while (count > 0)
  55. {
  56. size_t n_rw = safe_rw (fd, ptr, count);
  57. if (n_rw == (size_t) -1)
  58. break;
  59. if (n_rw == 0)
  60. {
  61. errno = ZERO_BYTE_TRANSFER_ERRNO;
  62. break;
  63. }
  64. total += n_rw;
  65. ptr += n_rw;
  66. count -= n_rw;
  67. }
  68. return total;
  69. }