Amr Rady
Amr Rady

Reputation: 1197

How to compare two (absolute) paths (given as char* ) in C and check if they are the same?

Given two paths as char*, I can't determine if the two paths are pointing to the same file. How to implement in C a platform-independent utility to check if paths are pointing to the same file or not.

Using strcmp will not work because on windows paths can contain \ or / Using ist_ino will not help because it does not work on windows

    char *fileName = du->getFileName();
    char *oldFileName = m_duPtr->getFileName();
    bool isSameFile = pathCompare(fileName, oldFileName) == 0;//(strcmp(fileName, oldFileName) == 0);
    if (isSameFile){
        stat(fileName, &pBuf);
        stat(oldFileName, &pBuf2);

        if (pBuf.st_ino == pBuf2.st_ino){
            bRet = true;
        }
    }

Upvotes: 3

Views: 158

Answers (1)

Joshua
Joshua

Reputation: 43290

You can't. Hard links also exist on Windows and the C standard library has no methods for operating on them.

Plausible solutions to the larger problem: link against cygwin1.dll and use the st_ino method. You omitted st_dev from your sample code and need to put it back.

While there is an actual way to accomplish this on Windows, it involves ntdll methods and I had to read Cygwin's code to find out how to do it.

The methods are NtGetFileInformationByHandle and NtFsGetVolumeInformationNyHandle. There are documented kernel32 calls that claim to do the same thing. See the cygwin source code for why they don't work right (buggy fs drivers).

Upvotes: 1

Related Questions