2016-11-12 60 views
0

我的操作系统是linux。我用C编程。我知道我可以使用lstat()来识别软链接,即使用S_ISLNK(st.st_mode)。但是我怎样才能认识到这个链接是硬链接?如果链接是硬链接,它将被视为常规文件。但是,我也想将常规文件与硬链接区分开来。有没有办法处理这种情况?如何使用lstat()确定是否硬连接

+0

当然,如果它不是一个软链接,那么它应该是一个硬链接? –

+0

常规文件*是*硬链接。 – wildplasser

回答

2

但是我怎样才能认识到这个链接是硬链接?

你不行。

“硬链接”实际上并没有什么特别之处。这只是一个目录条目,恰好指向磁盘上的相同数据,而不是其他目录条目。 只有可靠地识别硬链接的方法是将全部文件系统上的路径映射到inode,然后查看哪些路径指向相同的值。

0

struct stat具有st_nlink成员的硬链接数。它大于1,文件正在被指定为实际文件内容的硬链接之一。

struct stat { 
    dev_t  st_dev;  /* ID of device containing file */ 
    ino_t  st_ino;  /* inode number */ 
    mode_t st_mode; /* protection */ 
    nlink_t st_nlink; /* number of hard links */ 
    uid_t  st_uid;  /* user ID of owner */ 
    gid_t  st_gid;  /* group ID of owner */ 
    dev_t  st_rdev; /* device ID (if special file) */ 
    off_t  st_size; /* total size, in bytes */ 
    blksize_t st_blksize; /* blocksize for file system I/O */ 
    blkcnt_t st_blocks; /* number of 512B blocks allocated */ 
    time_t st_atime; /* time of last access */ 
    time_t st_mtime; /* time of last modification */ 
    time_t st_ctime; /* time of last status change */ 
}; 

下面是示例程序:

#include <sys/types.h> 
#include <sys/stat.h> 
#include <unistd.h> 
int main() 
{ 
    struct stat buf = {0}; 
    lstat("origfile", &buf); 
    printf("number of hard links for origfile: %d\n", buf.st_nlink); 
} 

输出:

$ touch origfile 
$ ./a.out 
number of hard links for origfile: 1 
$ ln origfile hardlink1 
$ ./a.out 
number of hard links for origfile: 2 
$ ln origfile hardlink2 
$ ./a.out 
number of hard links for origfile: 3 
相关问题