Reputation: 184
We have a function in straight C that is intended to tell us if two file references refer to the same file. Right now it first checks to see if the passed in parameters are actually the same pointer, and if not, it looks at the characters to see if the strings of characters are the same. But that doesn't account for the possibility of different ways to refer to the same file. For example...
"/d1/d2/d3/theFile" compared to "../d3/theFile"
Those could be the same file or not, depending on the directory structure and where the current point of reference is. I'd like to improve the following function to be able to check to see if the string reference to a file refers to the same file as another string...
static bool is_same_file (const char *f1, const char *f2) {
if (f1==f2)
return true;
return (0==strcmp(f1, f2));
}
I imagine that it might be possible to try opening both files and use that in some way. But I don't know how to check to see if the opened files are the same physical file on the drive, and not just coincidentally the same file that happen to exist in different directories. In C#, there's a FileInfo class that can be used to find a file based on that reference string, and then you can compare complete directory information, file name, and so on. Is there a way to do something similar in C?
Upvotes: 0
Views: 119
Reputation: 781255
On a POSIX system you can use stat()
to check if they have the same inode number on the same filesystem.
You should also check the generation number, to handle a race condition due to the file being deleted and a new file getting its inode number between the two calls.
#include <sys/stat.h>
static bool is_same_file (const char *f1, const char *f2) {
struct stat s1, s2;
if (stat(f1, &s1) < 0)) {
perror("stat f1");
return false;
}
if (stat(f2, &s2) < 0)) {
perror("stat f2");
return false;
}
return s1.st_dev == s2.st_dev && s1.st_ino == st.st_ino && s1.st_gen == s2.st_gen;
}
Upvotes: 2