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.


// 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]);

if (!realpath(argv[1], path)) {

printf("%s\n", path);

No comments: