Tuesday, June 2, 2009

What's the Absolute Path to a File?

There's no standard command that gives you the absolute path to a file. That's insane. Here's an implementation.

Yes, it resolves symlinks and works on directories, too.

I couldn't figure out how to get Blogger to stop re-formatting my code, so I passed it through this, web-based, C#-formatting tool (!), and now it seems to look okay.

Argh.

// realpath - what's the real path to a file?
// Turn relative paths into absolute paths,
// resolve '.' and '..',
// follow symlinks

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
char path[_POSIX_PATH_MAX];

if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
exit(EINVAL);
}

if (!realpath(argv[1], path)) {
perror(NULL);
exit(errno);
}

printf("%s\n", path);
return(0);
}

No comments: