std::filesystem::path::compare

Compares the lexical representations of the path and another path.

# Declarations

int compare( const path& p ) const noexcept;

(since C++17)

int compare( const string_type& str ) const;
int compare( std::basic_string_view<value_type> str ) const;

(since C++17)

int compare( const value_type* s ) const;

(since C++17)

# Parameters

# Return value

A value less than 0 if the path is lexicographically less than the given path.

# Notes

For two-way comparisons, binary operators may be more suitable.

# Example

#include <filesystem>
#include <iostream>
#include <string_view>
namespace fs = std::filesystem;
 
void demo(fs::path p1, fs::path p2, std::string_view msg)
{
    std::cout << p1;
    const int rc = p1.compare(p2); 
    if (rc < 0)
        std::cout << " < ";
    else if (rc > 0)
        std::cout << " > ";
    else
        std::cout << " == ";
    std::cout << p2 << " \t: " << msg << '\n';
}
 
int main()
{
    demo("/a/b/", "/a/b/", "simple");
    demo("/a/b/", "/a/b/c", "simple");
    demo("/a/b/../b", "/a/b", "no canonical conversion");
    demo("/a/b", "/a/b/.", "no canonical conversion");
    demo("/a/b/", "a/c", "absolute paths order after relative ones");
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2936C++17compared all path elements directlyroot name and root directory handled separately

# See also