s_getline.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include "String.h"
  5. /* Append an input line to a String.
  6. *
  7. * Returns a pointer to the character string (or 0).
  8. * Leading whitespace and newlines are removed.
  9. *
  10. * Empty lines and lines starting with '#' are ignored.
  11. */
  12. extern char *
  13. s_getline(Biobuf *fp, String *to)
  14. {
  15. int c;
  16. int len=0;
  17. s_terminate(to);
  18. /* end of input */
  19. if ((c = Bgetc(fp)) < 0)
  20. return 0;
  21. /* take care of inconsequentials */
  22. for(;;) {
  23. /* eat leading white */
  24. while(c==' ' || c=='\t' || c=='\n' || c=='\r')
  25. c = Bgetc(fp);
  26. if(c < 0)
  27. return 0;
  28. /* take care of comments */
  29. if(c == '#'){
  30. do {
  31. c = Bgetc(fp);
  32. if(c < 0)
  33. return 0;
  34. } while(c != '\n');
  35. continue;
  36. }
  37. /* if we got here, we've gotten something useful */
  38. break;
  39. }
  40. /* gather up a line */
  41. for(;;) {
  42. len++;
  43. switch(c) {
  44. case -1:
  45. s_terminate(to);
  46. return len ? to->ptr-len : 0;
  47. case '\\':
  48. c = Bgetc(fp);
  49. if (c != '\n') {
  50. s_putc(to, '\\');
  51. s_putc(to, c);
  52. }
  53. break;
  54. case '\n':
  55. s_terminate(to);
  56. return len ? to->ptr-len : 0;
  57. default:
  58. s_putc(to, c);
  59. break;
  60. }
  61. c = Bgetc(fp);
  62. }
  63. return 0;
  64. }