Created
January 29, 2016 19:29
-
-
Save danielgracia/53801bb48c7505d0bc7c to your computer and use it in GitHub Desktop.
shortpath (nerdsniped)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <libgen.h> | |
#include <errno.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <pwd.h> | |
char* homedir() { | |
char *homedir = getenv("HOME"); | |
if(homedir == NULL) { | |
homedir = getpwuid(getuid())->pw_dir; | |
} | |
return homedir; | |
} | |
char* currdir() { | |
char *buf = malloc(1024 * sizeof(char)); | |
if(getcwd(buf, 1024) == NULL) { | |
int errnum = errno; | |
fprintf(stderr, "%s\n", strerror(errnum)); | |
exit(errnum); | |
} | |
return buf; | |
} | |
bool startwith(const char *str, const char *prefix) { | |
return strncmp(prefix, str, strlen(prefix)) == 0; | |
} | |
int countsegments(const char *str) { | |
int result = 0; | |
for(const char *c = str; *c != '\0'; c++) { | |
if(*c == '/') result++; | |
} | |
return result; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
char *cdir = currdir(), *hdir = homedir(); | |
char *start = "/"; | |
char *ndir = malloc(strlen(cdir) * sizeof(char)); | |
bool home = startwith(cdir, hdir); | |
if(home) { | |
strncpy(ndir, cdir + strlen(hdir) + 1, strlen(cdir)); | |
start = "~/"; | |
} else { | |
strncpy(ndir, cdir + 1, strlen(cdir)); | |
} | |
free(cdir); | |
if(strlen(ndir) == 0) { | |
if(home) puts("~"); | |
else puts("/"); | |
return 0; | |
} | |
char *base = basename(ndir); | |
int segments = countsegments(ndir); | |
printf("%s", start); | |
if (segments == 0) { | |
printf("%s", base); | |
} else if (segments > 0) { | |
char *token; | |
while ((token = strsep(&ndir, "/")) != NULL) { | |
if (strncmp(token, base, strlen(base)) == 0) { | |
printf("%s", token); | |
} else { | |
printf("%c/", token[0]); | |
} | |
} | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment