I'd just like to get some pointers on my newbie-ish C here. The intention is to have an environment variable provide the "prefix" for any paths this app needs.
For example, APP_PREFIX
could be /opt/app
, a path the app wanted to get could be /etc/app.conf
, and so app_path("/etc/app.conf")
should return /opt/app/etc/app.conf
.
I realise this is currently sensitive to leading/trailing slashes; I just wanted to make sure I'm on the right track with this basic stuff. Be as pedantic as you like – from outright bugs down to style and convention.
It compiles with no warnings on Mac OS X with gcc -Wall -pedantic ...
, and does what I expect it to. On Linux, I had to compile with libbsd, and #include <bsd/string.h>
for strlcpy()
and strlcat()
.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define APP_PREFIX_ENV_VAR "APP_PREFIX"
const char * app_path_prefix() {
char * env_prefix = getenv(APP_PREFIX_ENV_VAR);
if (env_prefix == NULL) {
return "";
} else {
return env_prefix;
}
}
char * app_path(char * in_path) {
const char * prefix = app_path_prefix();
size_t prefix_len = strlen(prefix);
size_t out_size = prefix_len + strlen(in_path) + 1;
char * out = malloc(out_size);
strlcpy(out, prefix, prefix_len + 1);
strlcat(out, in_path, out_size);
return out;
}
int main(int argc, char ** argv) {
char * path = app_path(argv[1]);
printf("result: '%s'\n", path);
free(path);
return EXIT_SUCCESS;
}