util.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (C) 2002-2005 Roman Zippel <[email protected]>
  3. * Copyright (C) 2002-2005 Sam Ravnborg <[email protected]>
  4. *
  5. * Released under the terms of the GNU GPL v2.0.
  6. */
  7. #include <string.h>
  8. #include "lkc.h"
  9. /* file already present in list? If not add it */
  10. struct file *file_lookup(const char *name)
  11. {
  12. struct file *file;
  13. for (file = file_list; file; file = file->next) {
  14. if (!strcmp(name, file->name))
  15. return file;
  16. }
  17. file = malloc(sizeof(*file));
  18. memset(file, 0, sizeof(*file));
  19. file->name = strdup(name);
  20. file->next = file_list;
  21. file_list = file;
  22. return file;
  23. }
  24. /* Allocate initial growable sting */
  25. struct gstr str_new(void)
  26. {
  27. struct gstr gs;
  28. gs.s = malloc(sizeof(char) * 64);
  29. gs.len = 16;
  30. strcpy(gs.s, "\0");
  31. return gs;
  32. }
  33. /* Allocate and assign growable string */
  34. struct gstr str_assign(const char *s)
  35. {
  36. struct gstr gs;
  37. gs.s = strdup(s);
  38. gs.len = strlen(s) + 1;
  39. return gs;
  40. }
  41. /* Free storage for growable string */
  42. void str_free(struct gstr *gs)
  43. {
  44. if (gs->s)
  45. free(gs->s);
  46. gs->s = NULL;
  47. gs->len = 0;
  48. }
  49. /* Append to growable string */
  50. void str_append(struct gstr *gs, const char *s)
  51. {
  52. size_t l = strlen(gs->s) + strlen(s) + 1;
  53. if (l > gs->len) {
  54. gs->s = realloc(gs->s, l);
  55. gs->len = l;
  56. }
  57. strcat(gs->s, s);
  58. }
  59. /* Append printf formatted string to growable string */
  60. void str_printf(struct gstr *gs, const char *fmt, ...)
  61. {
  62. va_list ap;
  63. char s[10000]; /* big enough... */
  64. va_start(ap, fmt);
  65. vsnprintf(s, sizeof(s), fmt, ap);
  66. str_append(gs, s);
  67. va_end(ap);
  68. }
  69. /* Retrieve value of growable string */
  70. const char *str_get(struct gstr *gs)
  71. {
  72. return gs->s;
  73. }