utility.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * \AUTHOR: Serena Pallecchi student of Computer Science University of Pisa (Italy)
  3. * Commission from Faunalia Pontedera (PI) www.faunalia.it
  4. *
  5. * This program is free software under the GPL (>=v2)
  6. * Read the COPYING file that comes with GRASS for details.
  7. *
  8. */
  9. #include <string.h>
  10. #include <grass/gis.h>
  11. #include <grass/glocale.h>
  12. #include "utility.h"
  13. /*if occurred an error returns NULL */
  14. char *concatena(const char *str1, const char *str2)
  15. {
  16. char *conc = (char *)G_malloc(strlen(str1) + strlen(str2) + 1);
  17. if (conc == NULL) {
  18. return NULL;
  19. }
  20. strcpy(conc, str1);
  21. strcat(conc, str2);
  22. return conc;
  23. }
  24. /* split_arg returns the array of token find in linea separated by separatore presente
  25. * and write in argc the nummer of find token */
  26. /*if occurred an error returns NULL */
  27. char **split_arg(char *linea, char separatore, long *numerotoken)
  28. {
  29. char **argv; /* token array */
  30. char *copialinea; /* line copy */
  31. long i; /* find token number */
  32. long it; /* iterator */
  33. long num;
  34. int term; /* =0 if last token has not /0 */
  35. i = 0;
  36. term = 0;
  37. if (linea == NULL || linea[0] == '\0') {
  38. *numerotoken = 0;
  39. return NULL;
  40. }
  41. /* copy string */
  42. copialinea = (char *)G_malloc(strlen(linea) + 1);
  43. if (copialinea == NULL) {
  44. return NULL;
  45. }
  46. strcpy(copialinea, linea);
  47. argv = (char **)G_malloc(sizeof(char *));
  48. if (argv == NULL) {
  49. return NULL;
  50. }
  51. num = 0;
  52. for (it = 0; it < strlen(copialinea); it++) {
  53. if (copialinea[it] == separatore) {
  54. while (copialinea[it + 1] == separatore)
  55. it++;
  56. if (i != 0) {
  57. argv[i - 1] =
  58. G_realloc(argv[i - 1], (num + 1) * sizeof(char));
  59. argv[i - 1][num] = '\0';
  60. argv = (char **)G_realloc(argv, (i + 1) * sizeof(char *));
  61. num = 0;
  62. }
  63. if ((it + 1) == strlen(copialinea))
  64. term = 1;
  65. }
  66. else {
  67. if (num == 0) {
  68. i++;
  69. argv[i - 1] = G_malloc(sizeof(char));
  70. if (argv[i - 1] == NULL) {
  71. return NULL;
  72. }
  73. }
  74. else {
  75. argv[i - 1] =
  76. G_realloc(argv[i - 1], (num + 1) * sizeof(char));
  77. }
  78. argv[i - 1][num] = copialinea[it];
  79. num++;
  80. }
  81. }
  82. if (!term) {
  83. argv[i - 1] = G_realloc(argv[i - 1], (num + 1) * sizeof(char));
  84. argv[i - 1][num] = '\0';
  85. }
  86. *numerotoken = i;
  87. G_free(copialinea);
  88. return argv;
  89. }