For a namespace clean function, implement
_read
, otherwise implement
read
. The detailed implementation will depend
on the file handling functionality available.
A minimal implementation has no file system. Rather than failing, this function returns 0, indicating end-of-file.
#include <errno.h> #undef errno extern int errno; int _read (int file, char *ptr, int len) { return 0; /* EOF */ } /* _read () */
The OpenRISC 1000 BSP without a UART is very similar to the minimal implementation, but checks that the stream is standard input before returning 0. For all other streams it returns an error.
#include <errno.h> #include <unistd.h> #undef errno extern int errno; int _read (int file, char *ptr, int len) { if (STDIN_FILENO == file) { return 0; /* EOF */ } else { errno = EBADF; return -1; } } /* _read () */
The OpenRISC 1000 BSP with a UART is more complex. In this case, if the stream is standard input, a character is read (and optionally echoed) from the UART.
#include <errno.h> #include <unistd.h> #undef errno extern int errno; int _read (int file, char *buf, int len) { if (STDIN_FILENO == file) { int i; for (i = 0; i < len; i++) { buf[i] = _uart_getc (); #ifdef UART_AUTO_ECHO _uart_putc (buf[i]); #endif /* Return partial buffer if we get EOL */ if ('\n' == buf[i]) { return i; } } return i; /* Filled the buffer */ } else { errno = EBADF; return -1; } } /* _read () */
Caution | |
---|---|
The Or1ksim UART implementation only returns data when carriage return is hit, rather than as each character becomes available, which can lead to some unexpected behavior. |