Gio
Gio

Reputation: 1902

How to check whether two file names point to the same physical file

I have a program that accepts two file names as arguments: it reads the first file in order to create the second file. How can I ensure that the program won't overwrite the first file?

Restrictions:

Upvotes: 9

Views: 4089

Answers (6)

HelloSam
HelloSam

Reputation: 2345

If you mean the same inode, in bash, you could do

[ FILE1 -ef FILE2 ] && echo equal || echo difference

Combined with realpath/readlink, that should handle the soft-links as well.

Upvotes: 1

Tobu
Tobu

Reputation: 25426

On linux, open both files, and use fstat to check if st_ino (edit:) and st_dev are the same. open will follow symbolic links. Don't use stat directly, to prevent race conditions.

Upvotes: 14

mingos
mingos

Reputation: 24502

Maybe you could use the system() function in order to invoke some shell commands?

In bash, you would simply call:

stat -c %i filename

This displays the inode number of a file. You can compare two files this way and if their inodes are identical, it means they are hard links. The following call:

stat -c %N filename

will display the file's name and if it's a symbolic link, it'll print the file name it links to as well. It prints out only one name, even if the file it points to has hard links, so checking the symbolic link would require comparing inode numbers for the 2nd file and the file the symbolic links links to in order to make sure.

You could redirect stat output to a text file and then parse the file in your program.

Upvotes: 0

reko_t
reko_t

Reputation: 56430

You can use stat to get the file status, and check if the inode numbers are the same.

Upvotes: 0

anon
anon

Reputation:

The best bet is not to use filenames as identities. Instead, when you open the file for reading, lock it, using whatever mechanism your OS supports. When you then also open the file for writing, also lock it - if the lock fails, report an error.

Upvotes: 9

tvanfosson
tvanfosson

Reputation: 532505

If possible, open the first file read-only, (O_RDONLY) in LINUX. Then, if you try to open it again to write to it, you will get an error.

Upvotes: 3

Related Questions