argv_new.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 char * unescape_special_chars(const char *str)
  10. {
  11. char *res = NULL;
  12. char *s = NULL;
  13. for (s = strchr(str, '\\'); s; s = strchr(str, '\\')) {
  14. lub_string_catn(&res, str, s - str);
  15. str = s + 1;
  16. }
  17. lub_string_cat(&res, str);
  18. return res;
  19. }
  20. /*--------------------------------------------------------- */
  21. static void
  22. lub_argv_init(lub_argv_t *this,
  23. const char *line,
  24. size_t offset)
  25. {
  26. size_t len;
  27. const char *word;
  28. lub_arg_t *arg;
  29. bool_t quoted;
  30. /* first of all count the words in the line */
  31. this->argc = lub_argv_wordcount(line);
  32. /* allocate space to hold the vector */
  33. arg = this->argv = malloc(sizeof(lub_arg_t) * this->argc);
  34. if(arg)
  35. {
  36. /* then fill out the array with the words */
  37. for(word = lub_argv_nextword(line,&len,&offset,&quoted);
  38. *word;
  39. word = lub_argv_nextword(word+len,&len,&offset,&quoted))
  40. {
  41. char * tmp = lub_string_dupn(word,len);
  42. (*arg).arg = unescape_special_chars(tmp);
  43. lub_string_free(tmp);
  44. (*arg).offset = offset;
  45. (*arg).quoted = quoted;
  46. offset += len;
  47. if(BOOL_TRUE == quoted)
  48. {
  49. len += 1; /* account for terminating quotation mark */
  50. offset += 2; /* account for quotation marks */
  51. }
  52. arg++;
  53. }
  54. }
  55. else
  56. {
  57. /* failed to get memory so don't pretend otherwise */
  58. this->argc = 0;
  59. }
  60. }
  61. /*--------------------------------------------------------- */
  62. lub_argv_t *
  63. lub_argv_new(const char *line,
  64. size_t offset)
  65. {
  66. lub_argv_t *this;
  67. this = malloc(sizeof(lub_argv_t));
  68. if(NULL != this)
  69. {
  70. lub_argv_init(this,line,offset);
  71. }
  72. return this;
  73. }
  74. /*--------------------------------------------------------- */