Skip to content

Instantly share code, notes, and snippets.

@tuxillo
Created June 6, 2013 10:43
Show Gist options
  • Save tuxillo/5720680 to your computer and use it in GitHub Desktop.
Save tuxillo/5720680 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#define BASE "/myroot/"
struct node {
char data[128];
struct node *parent;
};
struct node narray[128];
#define SETP(n, p) (narray[n].parent = &narray[p])
#define SETN(n, s) (strcpy(narray[n].data, s))
char *
fpath1(struct node *n)
{
struct node *n1;
char *buf, *tmp;
buf = tmp = NULL;
for (n1 = n; n1->parent != NULL; n1 = n1->parent) {
if (buf == NULL)
asprintf(&tmp, "%s", n1->data);
else
asprintf(&tmp, "%s/%s", n1->data, buf);
if (tmp != NULL) {
if (buf)
free(buf);
buf = tmp;
} else {
goto fail;
}
}
return buf;
fail:
if (buf)
free(buf);
if (tmp)
free(tmp);
return NULL;
}
char *
fpath(struct node *n)
{
char **cnps = malloc(32 * sizeof(*cnps));
char **tmp = cnps;
struct node *n1;
char *fullpath;
size_t tlen, len;
int ret;
tlen = len = 0;
for (n1 = n; n1->parent != NULL; cnps++) {
*cnps = n1->data;
tlen += strlen(*cnps) + 1;
n1 = n1->parent;
}
fullpath = malloc(tlen + 1);
for (; cnps != tmp; cnps--) {
if (*cnps) {
ret = sprintf(fullpath + len, "%s/", *cnps);
len += ret;
}
}
fprintf(stdout, "%s\n", fullpath);
return fullpath;
}
int
main(int argc, char *argv[])
{
struct node *root;
char *line[16] = { "this", "is", "the", "path", "to", "the",
"place", "where", "I", "belong", "to" };
int i;
root = &narray[0];
root->parent = NULL;
for (i = 0; i < 11; i++) {
SETN(i+1, line[i]);
SETP(i+1, i);
}
for (i = 16; i >= 0; i--)
fprintf(stdout, "node%d=%s\n", i, fpath1(&narray[i]));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment