iob.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. */
  9. #include <rtthread.h>
  10. #include <sys/types.h>
  11. #include <stdio.h>
  12. #include <unistd.h>
  13. #ifdef RT_USING_POSIX_STDIO
  14. #include <posix/stdio.h>
  15. #endif /* RT_USING_POSIX_STDIO */
  16. #define DBG_TAG "picolibc.iob"
  17. #define DBG_LVL DBG_INFO
  18. #include <rtdbg.h>
  19. #ifdef TINY_STDIO
  20. static int __fputc(char c, FILE *file);
  21. static int __fgetc(FILE *file);
  22. static FILE __stdio_in = FDEV_SETUP_STREAM(NULL, __fgetc, NULL, _FDEV_SETUP_READ);
  23. static FILE __stdio_out = FDEV_SETUP_STREAM(__fputc, NULL, NULL, _FDEV_SETUP_WRITE);
  24. #ifdef __strong_reference
  25. #define STDIO_ALIAS(x) __strong_reference(stdout, x);
  26. #else
  27. #define STDIO_ALIAS(x) FILE *const x = &__stdio_out;
  28. #endif
  29. FILE *const stdin = &__stdio_in;
  30. FILE *const stdout = &__stdio_out;
  31. STDIO_ALIAS(stderr);
  32. static int __fputc(char c, FILE *file)
  33. {
  34. if (file == &__stdio_out)
  35. {
  36. #if defined(RT_USING_CONSOLE) && defined(RT_USING_DEVICE)
  37. rt_device_t console = rt_console_get_device();
  38. if (console)
  39. {
  40. rt_ssize_t rc = rt_device_write(console, -1, &c, 1);
  41. return rc > 0 ? rc : -1;
  42. }
  43. #endif /* defined(RT_USING_CONSOLE) && defined(RT_USING_DEVICE) */
  44. }
  45. return -1;
  46. }
  47. static int __fgetc(FILE *file)
  48. {
  49. if (file == &__stdio_in)
  50. {
  51. #ifdef RT_USING_POSIX_STDIO
  52. if (rt_posix_stdio_get_console() >= 0)
  53. {
  54. char c;
  55. int rc = read(STDIN_FILENO, &c, 1);
  56. return rc == 1 ? c : EOF;
  57. }
  58. #endif /* RT_USING_POSIX_STDIO */
  59. }
  60. return EOF;
  61. }
  62. #endif