argv_new.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * argv_new.c
  3. */
  4. #include "private.h"
  5. #include "lub/string.h"
  6. #include <stdlib.h>
  7. #include <string.h>
  8. /*--------------------------------------------------------- */
  9. static void lub_argv_init(lub_argv_t * this, const char *line, size_t offset)
  10. {
  11. size_t len;
  12. const char *word;
  13. lub_arg_t *arg;
  14. bool_t quoted;
  15. /* Save the whole line */
  16. this->line = lub_string_dup(line);
  17. /* first of all count the words in the line */
  18. this->argc = lub_argv_wordcount(line);
  19. /* allocate space to hold the vector */
  20. arg = this->argv = malloc(sizeof(lub_arg_t) * this->argc);
  21. if (arg) {
  22. /* then fill out the array with the words */
  23. for (word = lub_argv_nextword(line, &len, &offset, &quoted);
  24. *word;
  25. word =
  26. lub_argv_nextword(word + len, &len, &offset, &quoted)) {
  27. char *tmp = lub_string_dupn(word, len);
  28. (*arg).arg = lub_string_decode(tmp);
  29. lub_string_free(tmp);
  30. (*arg).offset = offset;
  31. (*arg).quoted = quoted;
  32. offset += len;
  33. if (BOOL_TRUE == quoted) {
  34. len += 1; /* account for terminating quotation mark */
  35. offset += 2; /* account for quotation marks */
  36. }
  37. arg++;
  38. }
  39. } else {
  40. /* failed to get memory so don't pretend otherwise */
  41. this->argc = 0;
  42. }
  43. }
  44. /*--------------------------------------------------------- */
  45. lub_argv_t *lub_argv_new(const char *line, size_t offset)
  46. {
  47. lub_argv_t *this;
  48. this = malloc(sizeof(lub_argv_t));
  49. if (NULL != this) {
  50. lub_argv_init(this, line, offset);
  51. }
  52. return this;
  53. }
  54. /*--------------------------------------------------------- */