writ_zeros.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*!
  2. * \file lib/gis/writ_zeros.c
  3. *
  4. * \brief GIS Library - Write zero functions.
  5. *
  6. * (C) 2001-2014 by the GRASS Development Team
  7. *
  8. * This program is free software under the GNU General Public License
  9. * (>=v2). Read the file COPYING that comes with GRASS for details.
  10. *
  11. * \author GRASS GIS Development Team
  12. *
  13. * \date 1999-2014
  14. */
  15. #include <unistd.h>
  16. #include <grass/gis.h>
  17. /**
  18. * \brief Writes <b>n</b> bytes of 9 to file descriptor <b>fd</b>
  19. *
  20. * \param[in] fd file descriptor
  21. * \param[in] n number of bytes to write
  22. * \return
  23. */
  24. void G_write_zeros(int fd, size_t n)
  25. {
  26. char zeros[1024];
  27. char *z;
  28. int i;
  29. if (n <= 0)
  30. return;
  31. /* There is a subtle gotcha to be avoided here.
  32. *
  33. * i must be an int for the write, but n (size_t) can be long or larger.
  34. * Must be careful not to cast long to int, hence
  35. * avoid i = n unless n is within range of int */
  36. /* fill zeros buffer with zeros */
  37. if (n > sizeof(zeros))
  38. i = sizeof(zeros);
  39. else
  40. i = n; /* this is ok here */
  41. z = zeros;
  42. while (i--)
  43. *z++ = 0;
  44. /* write n zeros to fd */
  45. while (n > 0) {
  46. if (n > sizeof(zeros))
  47. i = sizeof(zeros);
  48. else
  49. i = n; /* this is ok here */
  50. write(fd, zeros, i);
  51. n -= i;
  52. }
  53. }