Best way to determine if two path reference to same file in Windows?

后端 未结 11 1653
生来不讨喜
生来不讨喜 2020-11-30 11:23

How would I compare 2 strings to determine if they refer to the same path in Win32 using C/C++?

While this will handle a lot of cases it misses some things:

11条回答
  •  被撕碎了的回忆
    2020-11-30 11:51

    Filesystem library

    Since C++17 you can use the standard filesystem library. Include it using #include . You can access it even in older versions of C++, see footnote.

    The function you are looking for is equivalent, under namespace std::filesystem:

    bool std::filesystem::equivalent(const std::filesystem::path& p1, const filesystem::path& p2 );
    

    To summarize from the documentation: this function takes two paths as parameters and returns true if they reference the same file or directory, false otherwise. There is also a noexcept overload that takes a third parameter: an std::error_code in which to save any possible error.

    Example

    #include 
    #include 
    //...
    
    int main() {
        std::filesystem::path p1 = ".";
        std::filesystem::path p2 = fs::current_path();
        std::cout << std::filesystem::equivalent(p1, p2);
        //...
    }
    

    Output:

    1
    

    Using filesystem before C++17

    To use this library in versions prior to C++17 you have to enable experimental language features in your compiler and include the library in this way: #include . You can then use its functions under the namespace std::experimental::filesystem. Please note that the experimental filesystem library may differ from the C++17 one. See the documentation here.
    For example:

    #include 
    //...
    std::experimental::filesystem::equivalent(p1, p2);
    

提交回复
热议问题