《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.3 KiB

10 years ago
  1. #include <stdio.h>
  2. #define BUFSIZE 1024
  3. static char buf[BUFSIZE];
  4. /* *
  5. * readline - get a line from stdin
  6. * @prompt: the string to be written to stdout
  7. *
  8. * The readline() function will write the input string @prompt to
  9. * stdout first. If the @prompt is NULL or the empty string,
  10. * no prompt is issued.
  11. *
  12. * This function will keep on reading characters and saving them to buffer
  13. * 'buf' until '\n' or '\r' is encountered.
  14. *
  15. * Note that, if the length of string that will be read is longer than
  16. * buffer size, the end of string will be discarded.
  17. *
  18. * The readline() function returns the text of the line read. If some errors
  19. * are happened, NULL is returned. The return value is a global variable,
  20. * thus it should be copied before it is used.
  21. * */
  22. char *
  23. readline(const char *prompt) {
  24. if (prompt != NULL) {
  25. cprintf("%s", prompt);
  26. }
  27. int i = 0, c;
  28. while (1) {
  29. c = getchar();
  30. if (c < 0) {
  31. return NULL;
  32. }
  33. else if (c >= ' ' && i < BUFSIZE - 1) {
  34. cputchar(c);
  35. buf[i ++] = c;
  36. }
  37. else if (c == '\b' && i > 0) {
  38. cputchar(c);
  39. i --;
  40. }
  41. else if (c == '\n' || c == '\r') {
  42. cputchar(c);
  43. buf[i] = '\0';
  44. return buf;
  45. }
  46. }
  47. }