在C++17及之后的标准中,要判断两个路径是否指向同一个文件或目录,最可靠的方式是使用std::filesystem::equivalent函数。该函数由文件系统库提供,会基于底层操作系统的文件标识进行比对,而不是简单比较路径字符串,因此能正确处理符号链接、相对路径与绝对路径差异等情况。

一、equivalent函数基本介绍
equivalent函数定义在头文件<filesystem>中,其常见声明如下:
#include <filesystem> namespace fs = std::filesystem; // 函数原型 bool equivalent(const fs::path& p1, const fs::path& p2); bool equivalent(const fs::path& p1, const fs::path& p2, std::error_code& ec) noexcept;
第一种形式在出错时会抛出filesystem_error异常,第二种形式通过error_code返回错误,不会抛出异常,更适合对稳定性要求较高的服务程序。
二、基础使用示例
下面代码演示如何判断当前目录下的file.txt与绝对路径形式是否指向同一文件:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path p1 = "file.txt";
fs::path p2 = fs::absolute("file.txt");
try {
if (fs::equivalent(p1, p2)) {
std::cout << "两个路径指向同一文件" << std::endl;
} else {
std::cout << "两个路径指向不同文件" << std::endl;
}
} catch (const fs::filesystem_error& e) {
std::cerr << "发生错误: " << e.what() << std::endl;
}
return 0;
}
三、使用error_code避免异常
如果不希望异常中断流程,可传入std::error_code:
#include <iostream>
#include <filesystem>
#include <system_error>
namespace fs = std::filesystem;
int main() {
std::error_code ec;
bool same = fs::equivalent("a.txt", "b.txt", ec);
if (ec) {
std::cout << "比较失败: " << ec.message() << std::endl;
} else {
std::cout << (same ? "相同文件" : "不同文件") << std::endl;
}
return 0;
}
四、与字符串比较的区别
很多初学者会用p1.string() == p2.string()来比较,但这存在明显问题:
- 字符串比较无法识别./file.txt与file.txt是同一文件
- 无法处理符号链接指向同一实体的情况
- 不同大小写或分隔符写法可能导致误判(尤其在Windows与Linux差异下)
equivalent函数通过调用系统API获取文件唯一标识,能规避上述问题。
五、注意事项
| 场景 | 说明 |
|---|---|
| 路径不存在 | equivalent会抛出异常或设置error_code,不会返回true |
| 权限不足 | 无法访问文件元数据时比较失败 |
| 跨文件系统 | 只要标识相同仍可正确判断,但性能依赖系统实现 |
实际工程中建议在配置校验、缓存键生成、重复文件检测等场景优先使用equivalent,而不是自行解析路径字符串。
C++文件路径equivalent函数文件系统修改时间:2026-07-26 12:03:19