确定两个文件路径是否指向Linux / C下的同一个文件? [英] Determining if two file paths point to same file under Linux / C?

查看:250
本文介绍了确定两个文件路径是否指向Linux / C下的同一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux下,我有两个文件路径A和B:

  const char * A = ...; 
const char * B = ...;

现在我想确定,我应该如何 open(2)它们都是...

  int fda = open(A,...); 
int fdb = open(B,...);

...我会得到两个文件句柄在文件系统中的同一个文件中吗?



为了确定这一点,我想到了 stat(2)

  struct stat 
{
dev_t st_dev;
ino_t st_ino;




$ b

类似于(伪代码):

  bool IsSameFile(const char * sA,const char * sB)
{
stat A = stat( SA);
stat B = stat(sB);

return A.st_dev == B.st_dev&& A.st_ino == B.st_ino;





$ b有任何情况下,A和B是相同的文件,但 IsSameFile 会返回false?



是否有任何情况下,A和B是不同的文件,但 IsSameFile 会返回true?



有没有更好的方法来做我想要做的事?

A.st_ino
将返回 inode数字,所以你的程序在所有情况下都能正常工作。 / strong>您的系统中的文件。由于inode号码是唯一的,所以你的程序将正确地识别两个打开的文件是否相同。

您也可以检查 A.st_mode 的值来确定文件是否是符号链路即可。

Under Linux, I have two file paths A and B:

const char* A = ...;
const char* B = ...;

I now want to determine, should I open(2) them both...

int fda = open(A, ...);
int fdb = open(B, ...);

...will I get two filehandles open to the same file in the filesystem?

To determine this I thought of stat(2):

struct stat
{
    dev_t st_dev;
    ino_t st_ino;
    ...
}

Something like (pseudo-code):

bool IsSameFile(const char* sA, const char* sB)
{
    stat A = stat(sA);
    stat B = stat(sB);

    return A.st_dev == B.st_dev && A.st_ino == B.st_ino;
}

Are there any cases where A and B are the same file but IsSameFile would return false?

Are there any cases where A and B are different files but IsSameFile would return true?

Is there a better way to do what I'm trying to do?

解决方案

Your program will work fine in all the cases because A.st_ino will return the inode number of the files in your system. Since inode number is unique your program will correctly identify whether the two files opened are same or not.

You can also check the value of A.st_mode to find out whether the file is a symbolic link.

这篇关于确定两个文件路径是否指向Linux / C下的同一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆