linuxsymlinkfreepascal

Check if file is a symbolic link in Free Pascal


I’m reading various files and directories with the FindFirst and FindNext functions as described in the RTL documentation.

The only problem I have is that I can’t figure out if the file is a symbolic link. In the file attributes there is no constant or flag and I can’t find a function for testing for symbolic links.


Solution

  • Your original idea of using findfirst is best, since it is a portable solution (windows has symlinks too nowadays). The only thing to adapt is to request symlink checking in the attributes you pass to findfirst:

    uses sysutils;
    
    var info : TSearchrec;
    
    begin
      // the or fasymlink in the next file is necessary so that findfirst
      //     uses (fp)lstat instead of (fp)stat
      If FindFirst ('../*',faAnyFile or fasymlink ,Info)=0 then
         begin
        Repeat
          With Info do
            begin
            If (Attr and fasymlink) = fasymlink then
               Writeln('found symlink: ', info.name)
            else
               writeln('not a symlink: ', info.name,' ',attr);
            end;
        Until FindNext(info)<>0;
        end;
      FindClose(Info);
    end.