full-write.c 2.2 KB

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