检查文件是否是Freepascal中的符号链接

时间:2012-12-05 11:48:55

标签: linux pascal freepascal

我正在阅读使用FindFirst / FindNext函数的各种文件和目录,如here所述。

我唯一的问题是,我无法弄清楚文件是否是符号链接。在文件属性中没有常量或标志,我找不到用于测试符号链接的函数。

4 个答案:

答案 0 :(得分:2)

你可以使用BaseUnix的fpstat:

像这样的东西

uses baseUnix;
var s: stat;
fpstat(filname, s);
if s.st_mode = S_IFLNK then
  writeln('is link');

它还为您提供了有关该文件的许多其他信息(时间,大小......)

答案 1 :(得分:2)

你最初使用findfirst的想法是最好的,因为它是一个可移植的解决方案(windows现在也有符号链接)。唯一要适应的是请求传递给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.

答案 2 :(得分:1)

函数fpLStat就是答案:

var
  fileStat: stat;

begin 
  if fpLStat('path/to/file', fileStat) = 0 then
  begin
    if fpS_ISLNK(fileStat.st_mode) then
      Writeln ('File is a link');
    if fpS_ISREG(fileStat.st_mode) then
      Writeln ('File is a regular file');
    if fpS_ISDIR(fileStat.st_mode) then
      Writeln ('File is a directory');
    if fpS_ISCHR(fileStat.st_mode) then
      Writeln ('File is a character device file');
    if fpS_ISBLK(fileStat.st_mode) then
      Writeln ('File is a block device file');
    if fpS_ISFIFO(fileStat.st_mode) then
      Writeln ('File is a named pipe (FIFO)');
    if fpS_ISSOCK(fileStat.st_mode) then
      Writeln ('File is a socket');
  end;
end.

打印出来:

test_symlink
File is a link
test
File is a directory

答案 3 :(得分:0)

感谢您使用fpstat提示。但它似乎没有用。 我有两个文件,目录和目录的符号链接:

drwxrwxr-x   2 marc marc   4096 Okt  1 09:40 test
lrwxrwxrwx   1 marc marc     11 Dez  5 13:49 test_symlink -> /home/marc/

如果我对这些文件使用fpstat,我会得到:

Result of fstat on file test
Inode   : 23855105
Mode    : 16877
nlink   : 92
uid     : 1000
gid     : 1000
rdev    : 0
Size    : 12288
Blksize : 4096
Blocks  : 24
atime   : 1354711751
mtime   : 1354711747
ctime   : 1354711747

Result of fstat on file test_symlink
Inode   : 23855105
Mode    : 16877
nlink   : 92
uid     : 1000
gid     : 1000
rdev    : 0
Size    : 12288
Blksize : 4096
Blocks  : 24
atime   : 1354711751
mtime   : 1354711747
ctime   : 1354711747

属性st_mode没有区别。我认为fpstat获取链接目标的统计信息,这确实是一个目录......

相关问题