Skip to content

Instantly share code, notes, and snippets.

@vdudouyt
Last active November 19, 2016 07:20
Show Gist options
  • Save vdudouyt/992b945795723280393be90d297614ad to your computer and use it in GitHub Desktop.
Save vdudouyt/992b945795723280393be90d297614ad to your computer and use it in GitHub Desktop.
/* Canonicalize virtual path
* License: public domain
*/
void canonicalize(const char *path, char *output) {
do {
while(path[0] == '/') path++;
char *chunk_end = strchr(path, '/');
int chunk_length = chunk_end ? chunk_end - path : strlen(path);
if(chunk_length > 0 && !memcmp(path, ".", chunk_length)) {
path += chunk_length;
continue;
}
if(chunk_length > 0 && !memcmp(path, "..", chunk_length)) {
path += chunk_length;
char *prev = strrchr(output, '/');
if(prev) memset(prev, 0, strlen(prev));
continue;
}
strcat(output, "/");
strncat(output, path, chunk_length);
if(!chunk_end) {
if(chunk_length > 0) strcat(output, "/");
break;
}
path = chunk_end;
} while(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment