Michael Rawson
Michael Rawson

Reputation: 1975

How to condense relative filenames in C++

I'm building my own scripting language, just for fun (yes, I am aware of the difficulties of doing this), in C++ on Linux. This scripting language is going to have an import mechanism for including relative filenames in the interpreter pass stage.

So /home/michael/foo/bar might load ../bar/baz which might load ../foo/baz and so on. The problem I get is I end up having to load filenames like this: /home/michael/foo/../bar/../foo/baz (relative filenames added to the current directory, recursively). This looks very silly in error output, and I imagine will cause other problems later, not to mention being quite inefficient.

How (apart from writing my own filename parser) can I 'optimise' or 'compress' the filenames so that I only have to load /home/michael/foo/baz?

I'm not averse to using a library, but I'd prefer to use POSIX/GNU C libraries/extensions or Boost if possible, although from a precursory look I can't find anything in either of those that does what I want, although maybe I just don't know what to search for.

Upvotes: 0

Views: 89

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

POSIX defines a function named realpath that will resolve a path name for you. It sorts out .s, ..s, extra slashes, and will also resolve symbolic links.

Upvotes: 2

Nemanja Boric
Nemanja Boric

Reputation: 22157

Try realpath:

#include <stdlib.h>
#include <stdio.h>
int main()
{
  char resolved_path[100];
  realpath("/home/burgos/foo/../bar/../foo/baz", resolved_path);
  printf("\n%s\n",resolved_path);
  return 0;
}

Upvotes: 2

Related Questions