s_getline.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #include "String.h"
  13. /* Append an input line to a String.
  14. *
  15. * Returns a pointer to the character string (or 0).
  16. * Leading whitespace and newlines are removed.
  17. *
  18. * Empty lines and lines starting with '#' are ignored.
  19. */
  20. extern char *
  21. s_getline(Biobuf *fp, String *to)
  22. {
  23. int c;
  24. int len=0;
  25. s_terminate(to);
  26. /* end of input */
  27. if ((c = Bgetc(fp)) < 0)
  28. return 0;
  29. /* take care of inconsequentials */
  30. for(;;) {
  31. /* eat leading white */
  32. while(c==' ' || c=='\t' || c=='\n' || c=='\r')
  33. c = Bgetc(fp);
  34. if(c < 0)
  35. return 0;
  36. /* take care of comments */
  37. if(c == '#'){
  38. do {
  39. c = Bgetc(fp);
  40. if(c < 0)
  41. return 0;
  42. } while(c != '\n');
  43. continue;
  44. }
  45. /* if we got here, we've gotten something useful */
  46. break;
  47. }
  48. /* gather up a line */
  49. for(;;) {
  50. len++;
  51. switch(c) {
  52. case -1:
  53. s_terminate(to);
  54. return len ? to->ptr-len : 0;
  55. case '\\':
  56. c = Bgetc(fp);
  57. if (c != '\n') {
  58. s_putc(to, '\\');
  59. s_putc(to, c);
  60. }
  61. break;
  62. case '\n':
  63. s_terminate(to);
  64. return len ? to->ptr-len : 0;
  65. default:
  66. s_putc(to, c);
  67. break;
  68. }
  69. c = Bgetc(fp);
  70. }
  71. }