1

我正在使用此处所述的 FindFirst/FindNext 函数读取各种文件和目录。

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

4

4 回答 4

2

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.
于 2012-12-06T10:33:56.930 回答
2

您可以使用 BaseUnix 中的 fpstat:

像这样的东西

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

这也为您提供了有关文件的许多其他信息(时间、大小......)

于 2012-12-05T12:20:17.380 回答
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
于 2012-12-05T14:12:53.233 回答
0

Thanks for the hint using fpstat. But it does not seem to work. I have two files, a directory and a symlink to a directory:

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

If I use fpstat on these to files I get:

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

No difference in Attribute st_mode. I think that fpstat gets the stats of the link destination, which indeed is a directory...

于 2012-12-05T13:57:33.533 回答