fgets.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #define __fgetc_unlocked __libc_fgetc_unlocked
  8. #include "_stdio.h"
  9. #ifdef __DO_UNLOCKED
  10. char attribute_hidden *__fgets_unlocked(char *__restrict s, int n,
  11. register FILE * __restrict stream)
  12. {
  13. register char *p;
  14. int c;
  15. __STDIO_STREAM_VALIDATE(stream);
  16. #ifdef __UCLIBC_MJN3_ONLY__
  17. #warning CONSIDER: What should fgets do if n <= 0?
  18. #endif /* __UCLIBC_MJN3_ONLY__ */
  19. /* Should we assert here? Or set errno? Or just fail... */
  20. if (n <= 0) {
  21. /* __set_errno(EINVAL); */
  22. goto ERROR;
  23. }
  24. p = s;
  25. while (--n) {
  26. if (__STDIO_STREAM_CAN_USE_BUFFER_GET(stream)) {
  27. if ((*p++ = __STDIO_STREAM_BUFFER_GET(stream)) == '\n') {
  28. break;
  29. }
  30. } else {
  31. if ((c = __fgetc_unlocked(stream)) == EOF) {
  32. if (__FERROR_UNLOCKED(stream)) {
  33. goto ERROR;
  34. }
  35. break;
  36. }
  37. if ((*p++ = c) == '\n') {
  38. break;
  39. }
  40. }
  41. }
  42. #ifdef __UCLIBC_MJN3_ONLY__
  43. #warning CONSIDER: If n==1 and not at EOF, should fgets return an empty string?
  44. #endif /* __UCLIBC_MJN3_ONLY__ */
  45. if (p > s) {
  46. *p = 0;
  47. return s;
  48. }
  49. ERROR:
  50. return NULL;
  51. }
  52. weak_alias(__fgets_unlocked,fgets_unlocked);
  53. #ifndef __UCLIBC_HAS_THREADS__
  54. weak_alias(__fgets_unlocked,fgets);
  55. #endif
  56. #elif defined __UCLIBC_HAS_THREADS__
  57. char *fgets(char *__restrict s, int n,
  58. register FILE * __restrict stream)
  59. {
  60. char *retval;
  61. __STDIO_AUTO_THREADLOCK_VAR;
  62. __STDIO_AUTO_THREADLOCK(stream);
  63. retval = __fgets_unlocked(s, n, stream);
  64. __STDIO_AUTO_THREADUNLOCK(stream);
  65. return retval;
  66. }
  67. #endif