Skip to content

Commit

Permalink
Add resolve_path util function
Browse files Browse the repository at this point in the history
  • Loading branch information
JerziKaminsky committed Apr 14, 2017
1 parent 4b3e533 commit 8cfd2d4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
33 changes: 33 additions & 0 deletions common/util.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#define _XOPEN_SOURCE 500
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
Expand Down Expand Up @@ -118,3 +122,32 @@ uint32_t parse_color(const char *color) {
}
return res;
}

char* resolve_path(const char* path) {
struct stat sb;
char *resolved = NULL;
ssize_t r;

if (lstat(path, &sb) == -1) {
goto failed;
}
if(S_ISREG(sb.st_mode)) {
return strdup(path);
}
if (!(resolved = malloc(sb.st_size + 1))) {
return NULL;
}
r = readlink(path, resolved, sb.st_size);
if (r == -1) {
goto failed;
}
if (r > sb.st_size) {
goto failed;
}
resolved[r] = '\0';

return resolved;

failed:
return strdup(path);
}
6 changes: 6 additions & 0 deletions include/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,10 @@ pid_t get_parent_pid(pid_t pid);
*/
uint32_t parse_color(const char *color);

/**
* Given a path string, resolves symlinks to their targets and return the result
* If the path does not exist or is not a symlink a string copy of it is returned.
* Returns NULL on error. Caller must free the returned buffer.
*/
char* resolve_path(const char* path);
#endif

0 comments on commit 8cfd2d4

Please sign in to comment.