full-write.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* An interface to read and write that retries (if necessary) until complete.
  2. Copyright (C) 1993-1994, 1997-2006, 2009-2023 Free Software Foundation, Inc.
  3. This file is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as
  5. published by the Free Software Foundation; either version 2.1 of the
  6. License, or (at your option) any later version.
  7. This file 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 Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. /* Specification. */
  15. #ifdef FULL_READ
  16. # include "full-read.h"
  17. #else
  18. # include "full-write.h"
  19. #endif
  20. #include <errno.h>
  21. #ifdef FULL_READ
  22. # include "safe-read.h"
  23. # define safe_rw safe_read
  24. # define full_rw full_read
  25. # undef const
  26. # define const /* empty */
  27. #else
  28. # include "safe-write.h"
  29. # define safe_rw safe_write
  30. # define full_rw full_write
  31. #endif
  32. #ifdef FULL_READ
  33. /* Set errno to zero upon EOF. */
  34. # define ZERO_BYTE_TRANSFER_ERRNO 0
  35. #else
  36. /* Some buggy drivers return 0 when one tries to write beyond
  37. a device's end. (Example: Linux 1.2.13 on /dev/fd0.)
  38. Set errno to ENOSPC so they get a sensible diagnostic. */
  39. # define ZERO_BYTE_TRANSFER_ERRNO ENOSPC
  40. #endif
  41. /* Write(read) COUNT bytes at BUF to(from) descriptor FD, retrying if
  42. interrupted or if a partial write(read) occurs. Return the number
  43. of bytes transferred.
  44. When writing, set errno if fewer than COUNT bytes are written.
  45. When reading, if fewer than COUNT bytes are read, you must examine
  46. errno to distinguish failure from EOF (errno == 0). */
  47. size_t
  48. full_rw (int fd, const void *buf, size_t count)
  49. {
  50. size_t total = 0;
  51. const char *ptr = (const char *) buf;
  52. while (count > 0)
  53. {
  54. size_t n_rw = safe_rw (fd, ptr, count);
  55. if (n_rw == (size_t) -1)
  56. break;
  57. if (n_rw == 0)
  58. {
  59. errno = ZERO_BYTE_TRANSFER_ERRNO;
  60. break;
  61. }
  62. total += n_rw;
  63. ptr += n_rw;
  64. count -= n_rw;
  65. }
  66. return total;
  67. }