I assume your host is windows or unix (both support the ..
, .
, and /
meaning parent directory, current directory, and directory separator respectively). And that your library provides access to the posix-specified function getcwd()
which retrieves the current working directory of your program (i.e. the full path where output files will be written if opened without a path specification in their filename).
First call getcwd()
to retrieve the working directory. If the last character in that is a '/'
, prepend that working directory to your input string without modification. Otherwise prepend both it and the character '/'
to your string.
Then just process the string. Find the first instance of the string "../"
and remove the previous part of the path and the "../"
. For example, if the string is "/a/b/c/../foo"
the result will be "/a/b/foo"
. Repeat until no instances of "../"
in the string.
The only caveat is deciding what to do with strings like "/../"
(which are technically a path that cannot exist). Either leave that as "/"
(so you always get a path that is feasible) or report an error.
Once that is done, look for instances of "/./"
and replace them with a "/"
. This will turn strings like "/a/b/c/./"
into "/a/b/c/"
but will leave strings like "/a/b/c./"
(which specify a directory named "c."
within "/a/b"
) alone.
All of the above is just processing the string. Apart from the usage of getcwd()
, there is nothing that relies on the host environment. So the process will be the same regardless of whether a path actually exists.
A few bells and whistles might include making it work better with windows, such as treating '/'
and '\'
as equivalent, and coping with drive specifiers like "a:"
.
If you don't want to call getcwd()
(e.g. if your program does not rely on actually having a working directory, or if it has one that doesn't exist) then you will need to specify a starting condition. For example, where will a string like "../x/y/z"
end up?
What I've suggested does allow the .
character to be part of filenames (or directory names) which you may or may not want. Adjust as needed.