fgets.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Copyright (C) 2004 Manuel Novoa III <mjn3@codepoet.org>
  2. *
  3. * GNU Library General Public License (LGPL) version 2 or later.
  4. *
  5. * Dedicated to Toni. See uClibc/DEDICATION.mjn3 for details.
  6. */
  7. #include "_stdio.h"
  8. /* libc_hidden_proto(fgets_unlocked) */
  9. #ifdef __DO_UNLOCKED
  10. /* libc_hidden_proto(__fgetc_unlocked) */
  11. char *fgets_unlocked(char *__restrict s, int n,
  12. register FILE * __restrict stream)
  13. {
  14. register char *p;
  15. int c;
  16. __STDIO_STREAM_VALIDATE(stream);
  17. #ifdef __UCLIBC_MJN3_ONLY__
  18. #warning CONSIDER: What should fgets do if n <= 0?
  19. #endif /* __UCLIBC_MJN3_ONLY__ */
  20. /* Should we assert here? Or set errno? Or just fail... */
  21. if (n <= 0) {
  22. /* __set_errno(EINVAL); */
  23. goto ERROR;
  24. }
  25. p = s;
  26. while (--n) {
  27. if (__STDIO_STREAM_CAN_USE_BUFFER_GET(stream)) {
  28. if ((*p++ = __STDIO_STREAM_BUFFER_GET(stream)) == '\n') {
  29. break;
  30. }
  31. } else {
  32. if ((c = __fgetc_unlocked(stream)) == EOF) {
  33. if (__FERROR_UNLOCKED(stream)) {
  34. goto ERROR;
  35. }
  36. break;
  37. }
  38. if ((*p++ = c) == '\n') {
  39. break;
  40. }
  41. }
  42. }
  43. #ifdef __UCLIBC_MJN3_ONLY__
  44. #warning CONSIDER: If n==1 and not at EOF, should fgets return an empty string?
  45. #endif /* __UCLIBC_MJN3_ONLY__ */
  46. if (p > s) {
  47. *p = 0;
  48. return s;
  49. }
  50. ERROR:
  51. return NULL;
  52. }
  53. libc_hidden_def(fgets_unlocked)
  54. #ifndef __UCLIBC_HAS_THREADS__
  55. /* libc_hidden_proto(fgets) */
  56. strong_alias(fgets_unlocked,fgets)
  57. libc_hidden_def(fgets)
  58. #endif
  59. #elif defined __UCLIBC_HAS_THREADS__
  60. /* libc_hidden_proto(fgets) */
  61. char *fgets(char *__restrict s, int n,
  62. register FILE * __restrict stream)
  63. {
  64. char *retval;
  65. __STDIO_AUTO_THREADLOCK_VAR;
  66. __STDIO_AUTO_THREADLOCK(stream);
  67. retval = fgets_unlocked(s, n, stream);
  68. __STDIO_AUTO_THREADUNLOCK(stream);
  69. return retval;
  70. }
  71. libc_hidden_def(fgets)
  72. #endif