| STROPT(3) | Library Functions Manual | STROPT(3) |
stropt, stroptx, stropt2buf, stropt2str - Parse options from a string (it supports quotation, option arguments)
#include <stropt.h>
int stropt(const char *input, char **tags, char **args, char *buf);
int stroptx(const char *input, char *features, char *sep, int flags, char **tags, char **args, char *buf);
char *stropt2buf(void *buf, size_t size, char **tags, char **args, char sep, char eq);
char *stropt2str(char **tags, char **args, char sep, char eq);
This small library parses a list of options from a string. Options can be separated by spaces, commas, semicolons, tabs or new line. (e.g. uppercase,bold,underlined ). Options may have arguments (e.g. ro,noatime,uid=0,gid=0 ). It is possible to protect symbols and spaces using quote, double quote and backslash (e.g. values='1,2,3,4',equal== )
The following function lists the option tags and arguments (without modyfying the input string).
void parse_args(char *input) {
int tagc = stropt(input, NULL, NULL, NULL);
if(tagc > 0) {
char buf[strlen(input)+1];
char *tags[tagc];
char *args[tagc];
stropt(input, tags, args, buf);
for (int i=0; i<tagc; i++)
printf("%s = %s\n",tags[i], args[i]);
}
}
it is possible to use the same input string as the buffer for parsing (the value of the input string gets lost in this way).
void parse_args(char *input) {
int tagc = stropt(input, NULL, NULL, NULL);
if(tagc > 0) {
char *tags[tagc];
char *args[tagc];
stropt(input, tags, args, input);
for (int i=0; i<tagc; i++)
printf("%s = %s\n",tags[i], args[i]);
}
}
when options to parse have no arguments, args can be set to NULL.
void parse_args(char *input) {
int tagc = stropt(input, NULL, NULL, NULL);
if(tagc > 0) {
char buf[strlen(input)+1];
char *tags[tagc];
stropt(input, tags, NULL, buf);
for (int i=0; i<tagc; i++)
printf("%s \n",tags[i]);
}
}
The following complete program parses and re-encode a string of comma separated arguments deleting those which begin by an uppercase letter.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stropt.h>
char *delete_uppercase_options(const char *input) {
int tagc = stroptx(input, "", ",",STROPTX_ALLOW_MULTIPLE_SEP, NULL, NULL, NULL);
if(tagc > 0) {
char buf[strlen(input)+1];
char *tags[tagc];
int i;
stroptx(input, "", ",",STROPTX_ALLOW_MULTIPLE_SEP, tags, NULL, buf);
for (i = 0; i < tagc; i++)
if (tags[i] && isupper(tags[i][0]))
tags[i] = STROPTX_DELETED_TAG;
return stropt2str(tags, NULL, ',', '=');
} else
return NULL;
}
int main(int argc, char *argv[]) {
if (argc > 1) {
char *result = delete_uppercase_options(argv[1]);
printf("%s\n", result);
free(result);
}
return 0;
}
VirtualSquare. Project leader: Renzo Davoli.
| August 2020 | VirtualSquare |