2012-12-05 59 views
1

我正在使用FindFirst/FindNext函數讀取各種文件和目錄,如here所述。檢查文件是否是Freepascal中的符號鏈接

我唯一的問題是,我無法弄清楚文件是否是符號鏈接。在文件屬性中沒有常量或標誌,我找不到用於測試符號鏈接的函數。

+1

什麼操作系統?如果是Windows,是指Windows 7符號鏈接還是聯結重新分析點? –

+0

我正在Linux下開發。 – Marc

+0

自從Kylix以來,這個afaik已被抽象化。 (fasymlink),所以操作系統應該沒有問題,除非你使用舊的FPC或Delphi,它不會使Windows符號鏈接混亂。儘管如此,我還沒有用FPC測試Windows符號鏈接。 –

回答

2

你的原使用findfirst的想法是最好的,因爲它是一個便攜式解決方案(windows現在也有符號鏈接)。唯一適應的是請求符號鏈接檢查你通過的屬性找到第一個:

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

你可以使用fpstat從BaseUnix:

像這樣的事情

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

也爲您提供了大量有關該文件的其他信息(時間,大小...)

+0

你需要lstat。但是這使得它沒有很好的理由,它的操作系統特定 –

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獲取鏈接地址,這的確是一個目錄的統計...

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 
相關問題