source: MondoRescue/trunk/mondo/src/lib/mr_str.c@ 979

Last change on this file since 979 was 969, checked in by Bruno Cornec, 17 years ago

mr_str now contains all string functions (removal of mr_string from trunk)

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