Results 1 to 4 of 4

Thread: Dealing with paths in a cross-platform way.

  1. #1

    Dealing with paths in a cross-platform way.

    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
    Coders rule nr 1: Face ur bugz.. dont cage them with code, kill'em with ur cursor.

  2. #2
    PGD Community Manager AthenaOfDelphi's Avatar
    Join Date
    Dec 2004
    Location
    South Wales, UK
    Posts
    1,245
    Blog Entries
    2
    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.
    :: AthenaOfDelphi :: My Blog :: My Software ::

  3. #3
    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
    Peregrinus, expectavi pedes meos in cymbalis
    Nullus norvegicorum sole urinat

  4. #4
    Dohh. This what i've defined in the game lib:
    Code:
    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.
    Last edited by User137; 24-10-2010 at 10:55 AM.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •