source: MondoRescue/branches/2.2.9/mondo/src/common/mr_string.c@ 2178

Last change on this file since 2178 was 1917, checked in by Bruno Cornec, 16 years ago

mondo.libmondo-cli.patch (Mark Pinkerton <Mark.Pinkerton_at_emageon.com>) modified to not duplicate the newt initialization stuff (we should rather remove them in mondoarchive)

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