PDA

View Full Version : Dealing with paths in a cross-platform way.



chronozphere
23-10-2010, 06:28 PM
Hi guys,

It seems that windows uses '\' and linux uses '/' as a directory separator in paths. My code contains path constants. How should I deal with those?

Can one of the two slashes be used on both platforms?

Thanks :)

AthenaOfDelphi
23-10-2010, 07:05 PM
I would have a unit that provides this kind of thing and then use conditional defines to compile in the one that's appropriate to the platform.

That said, I do believe windows will allow you to use / instead of \. The one big difference there though is that I don't believe / will take you to the root of the current path like \ would.

As I say, I'd handle it using a platform support unit that adds in certain things like this. You are probably going to come across more things like this so one common library maybe a good place.

Depending on how you use them, you may also be able to use functions like includeTrailingPathDelimiter (formerly includeTrailingBackslash IIRC). Providing that's support by all the compilers, you'd only have to worry about paths entered by the user. Even if your compiler doesn't support that, you could provide it using conditional defines for those compilers that don't have it built it.

JSoftware
23-10-2010, 11:44 PM
FPC RTL file functions will convert either to the native path seperator. It'll also handle repeated seperators of diffent types, but if you want to be certain then use DirectorySeparator

User137
24-10-2010, 10:52 AM
Dohh. This what i've defined in the game lib:

const
{$IFDEF Windows}
PathChar = '\';
{$ELSE}
PathChar = '/';
{$ENDIF}

procedure FixPath(var path: string);
var i: integer; c: char;
begin
for i:=1 to length(path) do begin
c:=path[i];
if ((c='\') or (c='/')) and (c<>PathChar) then path[i]:=PathChar;
end;
end;
It will return the path that fits to current operating system. If there's nothing to fix it'll just return the same path it got as parameter.

edit: And i guess i keep using this because my code must be compatible with Lazarus and Delphi.