Various modules solving daily C developer tasks
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

string.c 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /******************************************************************************
  2. *
  3. * Copyright (c) 2017-2019 by Löwenware Ltd
  4. * Please, refer LICENSE file for legal information
  5. *
  6. ******************************************************************************/
  7. /**
  8. * @file string.c
  9. * @author Ilja Kartašov <ik@lowenware.com>
  10. * @brief cStuff string module implementation
  11. *
  12. * @see https://lowenware.com/
  13. */
  14. #include <stdio.h>
  15. #include <stdarg.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include "string.h"
  19. int
  20. cstuff_strcpy(char **out, const char *in)
  21. {
  22. return cstuff_strncpy(out, in, strlen(in));
  23. }
  24. int
  25. cstuff_strncpy(char **out, const char *in, int len)
  26. {
  27. char *s;
  28. if (!(s = malloc( len + 1 )))
  29. return -1;
  30. strncpy(s, in, len);
  31. s[len]=0;
  32. *out = s;
  33. return len;
  34. }
  35. int
  36. cstuff_strset(char **out, const char *in)
  37. {
  38. return cstuff_strnset(out, in, strlen(in));
  39. }
  40. int
  41. cstuff_strnset(char **out, const char *in, int len)
  42. {
  43. char *s;
  44. if (!(s = realloc(*out, len+1)))
  45. return -1;
  46. strncpy(s, in, len);
  47. s[len] = 0;
  48. *out = s;
  49. return len;
  50. }
  51. int
  52. cstuff_sprintf(char **out, const char *format, ...)
  53. {
  54. int result;
  55. va_list vl;
  56. va_start(vl, format);
  57. result = cstuff_vsprintf(out, format, vl);
  58. va_end(vl);
  59. return result;
  60. }
  61. int
  62. cstuff_vsprintf(char **out, const char *format, va_list args)
  63. {
  64. int result;
  65. va_list vc;
  66. char tmp, *s;
  67. va_copy(vc, args);
  68. result = vsnprintf(&tmp, 1, format, vc);
  69. va_end(vc);
  70. if (!(s = malloc(result + 1)))
  71. return -1;
  72. *out = s;
  73. result = vsnprintf(s, result+1, format, args);
  74. return result;
  75. }