4
0

full-write.c 2.3 KB

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