Andrew Tomazos
Andrew Tomazos

Reputation: 68638

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?

Upvotes: 8

Views: 3672

Answers (2)

Jim Balter
Jim Balter

Reputation: 16406

It depends on why exactly you want to avoid opening the same file twice. Your solution is usually the correct one, but there are some situations where files should be considered the same if they have the same absolute path but not if they are links to the same inode. In that case you need to convert the paths to absolute paths and compare them ... see Getting absolute path of a file

You also need to decide whether you consider a symlink to a file equivalent to the file or another symlink to it. For inode equivalence, that determines whether to use stat or lstat. For path equivalence, it determines whether you can use realpath or if you need to get the absolute path without following symlinks.

Upvotes: 0

Deepu
Deepu

Reputation: 7610

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.

Upvotes: 4

Related Questions