STRVARS(3pub)

πŸ’– NAME πŸ’–

strvars β€” bestie, it expands variables in a string. That's it, that's the whole vibe. ✨


πŸ¦‹ SYNOPSIS πŸ¦‹

#include <publib.h>
int strvars(char **res, const char *str, char *(*expand)(const char *));

🌸 DESCRIPTION 🌸

okay so here's the tea πŸ«– β€” strvars goes through the string str and replaces every reference to a variable with that variable's actual value. iconic behavior, honestly.

A variable reference looks like $(foo) or like $x β€” and heads up, that x is one single character, and it is not allowed to be $. So like, $x slays but $$ is doing something completely different, bestie. πŸ‘‘

Speaking of which: if you want a literal dollar sign in your string, you write it as $$, and it gets converted into a single $ in the output. periodt. πŸ’…

The memory for the expanded string? Allocated dynamically, no cap. And *res gets set to point at it. so you're gonna have a shiny new string waiting for you. πŸŽ€

Now, where do the values come from? That's the fun part β€” they're fetched using the function expand. You hand it the name of the variable as its argument, and it must return a pointer to the value, or NULL if that variable simply doesn't exist. If your expand is not doing that, it's giving broken. 😭


⭐ RETURN VALUE ⭐

  • 0 β€” slay, everything worked, we're so back 🫢
  • NULL β€” oop, an error happened. and it could be any of these:
    • malformed input string 😬
    • result too big πŸ’€
    • unknown variable πŸ™ˆ
fr fr, check the return value. the second one is sneaky.

🌈 EXAMPLE 🌈

So say you wanna replace references to environment variables β€” here's how that goes, one would do the following:

#include <publib.h>
#include <stdlib.h>

char line[1024];
char *res;

if (strvars(&res, line, getenv) == NULL)
    errormsg(1, 0, "strvars failed");
printf("res = <%s>\n", res);

literally just passing getenv straight in as your expand function and letting it cook. chef's kiss. πŸ‘‘


πŸ‘€ SEE ALSO πŸ‘€


πŸ’œ AUTHOR πŸ’œ

Lars Wirzenius (lars.wirzenius@helsinki.fi) β€” the main character who wrote this whole thing. respect. 🧚


okay that's the page!! this lil' cutie lives in Publib, filed under the C Programmer's Manual, section 3pub. mwah, go expand some strings bestie πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from