full-write.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 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. #ifdef HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. /* Specification. */
  19. #ifdef FULL_READ
  20. # include "full-read.h"
  21. #else
  22. # include "full-write.h"
  23. #endif
  24. #include <errno.h>
  25. #ifdef FULL_READ
  26. # include "safe-read.h"
  27. # define safe_rw safe_read
  28. # define full_rw full_read
  29. # undef const
  30. # define const /* empty */
  31. #else
  32. # include "safe-write.h"
  33. # define safe_rw safe_write
  34. # define full_rw full_write
  35. #endif
  36. #ifdef FULL_READ
  37. /* Set errno to zero upon EOF. */
  38. # define ZERO_BYTE_TRANSFER_ERRNO 0
  39. #else
  40. /* Some buggy drivers return 0 when one tries to write beyond
  41. a device's end. (Example: Linux 1.2.13 on /dev/fd0.)
  42. Set errno to ENOSPC so they get a sensible diagnostic. */
  43. # define ZERO_BYTE_TRANSFER_ERRNO ENOSPC
  44. #endif
  45. /* Write(read) COUNT bytes at BUF to(from) descriptor FD, retrying if
  46. interrupted or if a partial write(read) occurs. Return the number
  47. of bytes transferred.
  48. When writing, set errno if fewer than COUNT bytes are written.
  49. When reading, if fewer than COUNT bytes are read, you must examine
  50. errno to distinguish failure from EOF (errno == 0). */
  51. size_t
  52. full_rw (int fd, const void *buf, size_t count)
  53. {
  54. size_t total = 0;
  55. const char *ptr = buf;
  56. while (count > 0)
  57. {
  58. size_t n_rw = safe_rw (fd, ptr, count);
  59. if (n_rw == (size_t) -1)
  60. break;
  61. if (n_rw == 0)
  62. {
  63. errno = ZERO_BYTE_TRANSFER_ERRNO;
  64. break;
  65. }
  66. total += n_rw;
  67. ptr += n_rw;
  68. count -= n_rw;
  69. }
  70. return total;
  71. }