0
votes

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.

2
Can you use POSIX functions? Try realpath.Joseph Mansfield
@sftrabbit: That's exactly what I wanted, thank you! Post it as an answer?Michael Rawson

2 Answers

2
votes

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;
}
2
votes

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.