io.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /** @file io.c
  2. * @brief Enchanced base IO functions.
  3. */
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <assert.h>
  7. #include <errno.h>
  8. #include <stdio.h>
  9. /** @brief Writes data to file.
  10. *
  11. * The system write() can be interrupted by signal or can write less bytes
  12. * than specified. This function will continue to write data until all data
  13. * will be written or error occured.
  14. *
  15. * @param [in] fd File descriptor.
  16. * @param [in] buf Buffer to write.
  17. * @param [in] n Number of bytes to write.
  18. * @return Number of bytes written or < 0 on error.
  19. */
  20. ssize_t faux_write(int fd, const void *buf, size_t n) {
  21. ssize_t bytes_written = 0;
  22. size_t left = n;
  23. const void *data = buf;
  24. assert(fd != -1);
  25. assert(buf);
  26. if ((-1 == fd) || !buf)
  27. return -1;
  28. if (0 == n)
  29. return 0;
  30. do {
  31. bytes_written = write(fd, data, left);
  32. if (bytes_written < 0) {
  33. if (EINTR == errno)
  34. continue;
  35. return -1;
  36. }
  37. if (0 == bytes_written) // Insufficient space
  38. return -1;
  39. data += bytes_written;
  40. left = left - bytes_written;
  41. } while (left > 0);
  42. return n;
  43. }
  44. /** @brief Reads data from file.
  45. *
  46. * The system read() can be interrupted by signal or can read less bytes
  47. * than specified. This function will continue to read data until all data
  48. * will be readed or error occured.
  49. *
  50. * @param [in] fd File descriptor.
  51. * @param [in] buf Buffer to write.
  52. * @param [in] n Number of bytes to write.
  53. * @return Number of bytes readed or < 0 on error.
  54. */
  55. ssize_t faux_read(int fd, void *buf, size_t n) {
  56. ssize_t bytes_readed = 0;
  57. ssize_t total_readed = 0;
  58. size_t left = n;
  59. void *data = buf;
  60. assert(fd != -1);
  61. assert(buf);
  62. if ((-1 == fd) || !buf)
  63. return -1;
  64. if (0 == n)
  65. return 0;
  66. do {
  67. bytes_readed = read(fd, data, left);
  68. if (bytes_readed < 0) {
  69. if (EINTR == errno)
  70. continue;
  71. if (total_readed > 0)
  72. return total_readed;
  73. return -1;
  74. }
  75. if (0 == bytes_readed) // EOF
  76. return total_readed;
  77. data += bytes_readed;
  78. total_readed += bytes_readed;
  79. left = left - bytes_readed;
  80. } while (left > 0);
  81. return total_readed;
  82. }