argv_nextword.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * argv_nextword.c
  3. */
  4. #include <stddef.h>
  5. #include <ctype.h>
  6. #include "private.h"
  7. #include "lub/types.h"
  8. /*--------------------------------------------------------- */
  9. const char *lub_argv_nextword(const char *string,
  10. size_t * len, size_t * offset, bool_t * quoted)
  11. {
  12. const char *word;
  13. bool_t quote = BOOL_FALSE;
  14. *quoted = BOOL_FALSE;
  15. /* find the start of a word (not including an opening quote) */
  16. while (*string && isspace(*string)) {
  17. string++;
  18. (*offset)++;
  19. }
  20. if (*string == '\\') {
  21. string++;
  22. if (*string)
  23. string++;
  24. }
  25. /* is this the start of a quoted string ? */
  26. if (*string == '"') {
  27. quote = BOOL_TRUE;
  28. string++;
  29. }
  30. word = string;
  31. *len = 0;
  32. /* find the end of the word */
  33. while (*string) {
  34. if (*string == '\\') {
  35. string++;
  36. (*len)++;
  37. if (*string) {
  38. (*len)++;
  39. string++;
  40. }
  41. continue;
  42. }
  43. if ((BOOL_FALSE == quote) && isspace(*string)) {
  44. /* end of word */
  45. break;
  46. }
  47. if (*string == '"') {
  48. /* end of a quoted string */
  49. *quoted = BOOL_TRUE;
  50. break;
  51. }
  52. (*len)++;
  53. string++;
  54. }
  55. return word;
  56. }
  57. /*--------------------------------------------------------- */
  58. unsigned lub_argv_wordcount(const char *line)
  59. {
  60. const char *word;
  61. unsigned result = 0;
  62. size_t len = 0, offset = 0;
  63. bool_t quoted;
  64. for (word = lub_argv_nextword(line, &len, &offset, &quoted);
  65. *word;
  66. word = lub_argv_nextword(word + len, &len, &offset, &quoted)) {
  67. /* account for the terminating quotation mark */
  68. len += (BOOL_TRUE == quoted) ? 1 : 0;
  69. result++;
  70. }
  71. return result;
  72. }
  73. /*--------------------------------------------------------- */