Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if two file paths point to same file under Linux / C?

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?

like image 735
Andrew Tomazos Avatar asked Mar 27 '13 01:03

Andrew Tomazos


1 Answers

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.

like image 196
Deepu Avatar answered Sep 23 '22 21:09

Deepu