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



Question:

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:

  • The method must keep working when the file system supports (soft or hard) links
  • File permissions are fixed and it is only required that the first file is readable and the second file writeable
  • It should preferably be platform-neutral (although Linux is the primary target)


Solution:1

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.


Solution:2

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.


Solution:3

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.


Solution:4

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


Solution:5

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »