[Lazarus] Multi-platform console application, how to handle file paths?

Michael Van Canneyt michael at freepascal.org
Tue Oct 29 12:43:51 CET 2019

On Tue, 29 Oct 2019, Bo Berglund via lazarus wrote:

> I am writing a console application intended to be portable between
> Windows and Linux and it uses files on the file system for
> configuration and also for processing data.
> Since the path delimiter is different on Unix and Windows I believe I
> have to handle this in my code, but how?
> I could create all paths inside the application using Windows
> delimiters and then upon usage send them to a "platform filter" like
> FixPlatformPath() below, which returns the string with the proper
> delimiters for the platform.
> Or else I have to check wherever the paths are dealt with and put
> conditionals inside the code in many places.
> Either way it feels a bit convoluted.
> Is there a better way?
> function FixPlatformPath(PathIn: string): string;
> begin
>  {$ifdef UNIX}
>    Result:= StringReplace(PathIn, '\', PathDelim, [rfReplaceAll]);
>  {$else}
>    Result:= StringReplace(PathIn, '/', PathDelim, [rfReplaceAll]);
>  {$endif}
> end;
> This would apply to all functions where files are handled such as
> reading config data, creating data files or reading data files etc...

1. Don't hardcode '/' or '\', use the PathDelim constant instead.
    You will not need any ifdefs.

2. FPC does not care whether you use '\' or '/', and windows normally will
accept '/' as well.

3. your "fixplatformpath' exists in FPC, in 2 forms:


    There are many routines that handle all this transparently:



More information about the lazarus mailing list