source: MondoRescue/trunk/mondo/src/common/mr_string.c@ 863

Last change on this file since 863 was 863, checked in by Bruno Cornec, 18 years ago

merge -r838:862 $SVN_M/branches/stable

File size: 1.9 KB
RevLine 
[831]1/*
2 * mr_string.c - New generation of string handling functions
3 */
[828]4
[831]5#include <stdio.h>
6#include <string.h>
7
8/**
9 * Safe alternative to standard function strok()
10 * @param instr
11 * @param delims
12 * @param lastpos
13 * @return @p
14 * @note this function allocates memory that needs to be freed by caller
15 **/
[828]16char *mr_strtok(char *instr, const char *delims, int *lastpos)
17{
18
19 char *token = NULL;
20 char *strptr = NULL;
21 size_t pos1 = 0;
22 size_t pos2 = 0;
23
24 if (strlen(instr) <= *lastpos) {
25 *lastpos = 0;
26 return token;
27 }
28
29 strptr = instr + *lastpos;
30 pos2 = strspn(strptr, delims);
31 strptr += pos2;
32 pos1 = strcspn(strptr, delims);
33 token = malloc(sizeof(*token) * (pos1 + 1));
34 strncpy(token, strptr, pos1);
35 token[pos1] = '\0';
36 *lastpos = *lastpos + pos1 + pos2 + 1;
37
38 return token;
39}
40
41
[831]42/**
43 * Returns the string fed to it 'inptr' with all characters to escape given
44 * in 'toesc' prepended by escaping character 'escchr'.
45 * (Prepare strings for use in system() or popen() with this function.)
46 * @param instr
47 * @param toesc
48 * @param escchr
49 * @note this function allocates memory that needs to be freed by caller
50 **/
[828]51char *mr_stresc(char *instr, char *toesc, const char escchr)
52{
53
54 char *inptr = NULL;
55 char *retstr = NULL;
56 char *retptr = NULL;
57 char *escptr = NULL;
58 int cnt = 0;
59
60 inptr = instr;
61
62 // Count how many characters need escaping.
63 while (*inptr != '\0') {
64 escptr = toesc;
65 while (*escptr != '\0') {
66 if (*inptr == *escptr) {
67 // Found it, skip the rest.
68 cnt++;
[863]69 inptr++;
[828]70 break;
71 }
72 inptr++;
73 escptr++;
74 }
75 }
76 inptr = instr;
77
78 retstr = (char *) malloc(strlen(inptr) + cnt + 1);
79 retptr = retstr;
80
81 // Prepend specified characters with escape character.
82 while (*inptr != '\0') {
83 escptr = toesc;
84 while (*escptr != '\0') {
85 if (*inptr == *escptr) {
86 // Found it, skip the rest.
87 *retptr = escchr;
88 retptr++;
89 break;
90 }
91 escptr++;
92 }
93 *retptr = *inptr;
94 retptr++;
95 inptr++;
96 }
97 *retptr = '\0';
98
99 return retstr;
100
101}
Note: See TracBrowser for help on using the repository browser.