1
0

stdio.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * File : stdio.c
  3. * Brief : stdio for newlib
  4. *
  5. * This file is part of RT-Thread RTOS
  6. * COPYRIGHT (C) 2006 - 2017, RT-Thread Development Team
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * Change Logs:
  23. * Date Author Notes
  24. * 2017/10/15 bernard the first version
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <rtthread.h>
  29. #include "libc.h"
  30. #define STDIO_DEVICE_NAME_MAX 32
  31. static FILE* std_console = NULL;
  32. int libc_stdio_set_console(const char* device_name, int mode)
  33. {
  34. FILE *fp;
  35. char name[STDIO_DEVICE_NAME_MAX];
  36. char *file_mode;
  37. snprintf(name, sizeof(name) - 1, "/dev/%s", device_name);
  38. name[STDIO_DEVICE_NAME_MAX - 1] = '\0';
  39. if (mode == O_RDWR) file_mode = "r+";
  40. else if (mode == O_WRONLY) file_mode = "wb";
  41. else if (mode == O_RDONLY) file_mode = "rb";
  42. fp = fopen(name, file_mode);
  43. if (fp)
  44. {
  45. setvbuf(fp, NULL, _IONBF, 0);
  46. if (std_console)
  47. {
  48. fclose(std_console);
  49. std_console = NULL;
  50. }
  51. std_console = fp;
  52. if (mode == O_RDWR)
  53. {
  54. _GLOBAL_REENT->_stdin = std_console;
  55. }
  56. else
  57. {
  58. _GLOBAL_REENT->_stdin = NULL;
  59. }
  60. if (mode == O_RDONLY)
  61. {
  62. _GLOBAL_REENT->_stdout = NULL;
  63. _GLOBAL_REENT->_stderr = NULL;
  64. }
  65. else
  66. {
  67. _GLOBAL_REENT->_stdout = std_console;
  68. _GLOBAL_REENT->_stderr = std_console;
  69. }
  70. _GLOBAL_REENT->__sdidinit = 1;
  71. }
  72. return fileno(std_console);
  73. }