Last change
on this file since 828 was 828, checked in by andree, 18 years ago |
Add new file with new generation string handling functions.
(File is currently not used yet.)
|
File size:
1.6 KB
|
Rev | Line | |
---|
[828] | 1 | // New generation of string handling functions
|
---|
| 2 |
|
---|
| 3 |
|
---|
| 4 | // Safe alternative to standard function strok()
|
---|
| 5 | char *mr_strtok(char *instr, const char *delims, int *lastpos)
|
---|
| 6 | {
|
---|
| 7 |
|
---|
| 8 | char *token = NULL;
|
---|
| 9 | char *strptr = NULL;
|
---|
| 10 | size_t pos1 = 0;
|
---|
| 11 | size_t pos2 = 0;
|
---|
| 12 |
|
---|
| 13 | if (strlen(instr) <= *lastpos) {
|
---|
| 14 | *lastpos = 0;
|
---|
| 15 | return token;
|
---|
| 16 | }
|
---|
| 17 |
|
---|
| 18 | strptr = instr + *lastpos;
|
---|
| 19 | pos2 = strspn(strptr, delims);
|
---|
| 20 | strptr += pos2;
|
---|
| 21 | pos1 = strcspn(strptr, delims);
|
---|
| 22 | token = malloc(sizeof(*token) * (pos1 + 1));
|
---|
| 23 | strncpy(token, strptr, pos1);
|
---|
| 24 | token[pos1] = '\0';
|
---|
| 25 | *lastpos = *lastpos + pos1 + pos2 + 1;
|
---|
| 26 |
|
---|
| 27 | return token;
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 |
|
---|
| 31 | // Returns the string fed to it 'inptr' with all characters to escape given
|
---|
| 32 | // in 'toesc' prepended by escaping character 'escchr'.
|
---|
| 33 | // (Prepare strings for use in system() or popen() with this function.)
|
---|
| 34 | char *mr_stresc(char *instr, char *toesc, const char escchr)
|
---|
| 35 | {
|
---|
| 36 |
|
---|
| 37 | char *inptr = NULL;
|
---|
| 38 | char *retstr = NULL;
|
---|
| 39 | char *retptr = NULL;
|
---|
| 40 | char *escptr = NULL;
|
---|
| 41 | int cnt = 0;
|
---|
| 42 |
|
---|
| 43 | inptr = instr;
|
---|
| 44 |
|
---|
| 45 | // Count how many characters need escaping.
|
---|
| 46 | while (*inptr != '\0') {
|
---|
| 47 | escptr = toesc;
|
---|
| 48 | while (*escptr != '\0') {
|
---|
| 49 | if (*inptr == *escptr) {
|
---|
| 50 | // Found it, skip the rest.
|
---|
| 51 | cnt++;
|
---|
| 52 | break;
|
---|
| 53 | }
|
---|
| 54 | inptr++;
|
---|
| 55 | escptr++;
|
---|
| 56 | }
|
---|
| 57 | }
|
---|
| 58 | inptr = instr;
|
---|
| 59 |
|
---|
| 60 | retstr = (char *) malloc(strlen(inptr) + cnt + 1);
|
---|
| 61 | retptr = retstr;
|
---|
| 62 |
|
---|
| 63 | // Prepend specified characters with escape character.
|
---|
| 64 | while (*inptr != '\0') {
|
---|
| 65 | escptr = toesc;
|
---|
| 66 | while (*escptr != '\0') {
|
---|
| 67 | if (*inptr == *escptr) {
|
---|
| 68 | // Found it, skip the rest.
|
---|
| 69 | *retptr = escchr;
|
---|
| 70 | retptr++;
|
---|
| 71 | break;
|
---|
| 72 | }
|
---|
| 73 | escptr++;
|
---|
| 74 | }
|
---|
| 75 | *retptr = *inptr;
|
---|
| 76 | retptr++;
|
---|
| 77 | inptr++;
|
---|
| 78 | }
|
---|
| 79 | *retptr = '\0';
|
---|
| 80 |
|
---|
| 81 | return retstr;
|
---|
| 82 |
|
---|
| 83 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.