Search code examples
freepascallazarus

What is opposite of ExtractRelativePath in Pascal?


I often use ExtractRelativePath to get the relative path between two path. But i cannot see any function opposite to it. This is an example from freepascal.org:

Uses sysutils;

Procedure Testit (FromDir,ToDir : String);

begin
  Write ('From "',FromDir,'" to "',ToDir,'" via "');
  Writeln (ExtractRelativePath(FromDir,ToDir),'"');
end;

Begin
 Testit ('/pp/src/compiler','/pp/bin/win32/ppc386');
 Testit ('/pp/bin/win32/ppc386','/pp/src/compiler');
 Testit ('e:/pp/bin/win32/ppc386','d:/pp/src/compiler');
 Testit ('e:\pp\bin\win32\ppc386','d:\pp\src\compiler');
End.

Output of this program

From "/pp/src/compiler" to "/pp/bin/win32/ppc386" via "../bin/win32/ppc386"
From "/pp/bin/win32/ppc386" to "/pp/src/compiler" via "../../src/compiler"
From "e:/pp/bin/win32/ppc386" to "d:/pp/src/compiler" via "../../src/compiler"
From "e:\pp\bin\win32\ppc386" to "d:\pp\src\compiler" via "../../src/compiler"

I need a function F to perform reverse action of ExtractRelativePath, for example:

F('/pp/src/compiler', '../bin/win32/ppc386') return '/pp/bin/win32/ppc386'.

Do you know any function like this? Thank you in advance.


Solution

  • Yes, sure. http://docwiki.embarcadero.com/Libraries/XE5/en/System.IOUtils.TPath.Combine

    System.IOUtils.TPath.Combine

      class function Combine(const Path1, Path2: string): string; inline; static;
    

    Description

    Combines two paths strings.

    Call Combine to obtain a new combined path from two distinct paths. If the second path is absolute, Combine returns it directly; otherwise Combine returns the first path concatenated with the second one.


    Above was written when the question was tagged by

    Now, for FPC simple scan through SysUtils sources lands you onto

    • c:\codetyphon\fpcsrc\rtl\objpas\sysutils\finah.inc

    Which has

    function ConcatPaths(const Paths: array of String): String;
    

    Which is documented at

    ConcatPaths

    Concatenate an array of paths to form a single path

    Declaration

    Source position: finah.inc line 42 function ConcatPaths( const Paths: array of ):;

    Description

    ConcatPaths will concatenate the different path components in Paths to a single path. It will insert directory separators between the various components of the path as needed. No directory separators will be added to the beginning or the end of the path, and none will be taken away.

    Example

    program ex96;
    
    { This program demonstrates the Concatpaths function }
    
    uses sysutils;
    
    begin
      // will write /this/path/more/levels/
      Writeln(ConcatPaths(['/this/','path','more/levels/']));
      // will write this/path/more/levels/
      Writeln(ConcatPaths(['this/','path','more/levels/']));
      // will write this/path/more/levels
      Writeln(ConcatPaths(['this/','path','more/levels']));
    end.