从 Boost.Filesystem v3 开始,检查它是否是常规文件已经可以满足您的需求。下面是一个简单的代码:
#include <boost/filesystem.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main(int argc, char* argv[]) {
if (argc > 1) {
auto status = fs::status(argv[1]);
if (status.type() == fs::regular_file)
std::cout << argv[1] << " is a valid path." << std::endl;
else
std::cout << argv[1] << " is not a valid path." << std::endl;
if (fs::symlink_status(argv[1]).type() == fs::symlink_file)
std::cout << "It is also a symlink." << std::endl;
} else {
std::cerr << "A path must be given." << std::endl;
}
return 0;
}
以下是一些输出:
% ./fstest /bin # it is a symlink path
/bin is not a valid path.
It is also a symlink.
% ./fstest /bin/ # it is a symlink path but dereferenced? (trailing /)
/bin/ is not a valid path.
% ./fstest /bin/zsoelim # it is a symlink
/bin/zsoelim is a valid path.
It is also a symlink.
% ./fstest /bin/soelim # it is not a symlink
/bin/soelim is a valid path.
如您所见,boost::filesystem::status(path)
返回有关实际路径的信息,无论它是否是符号链接(跟随到实际位置)。另一方面,boost::filesystem::symlink_status(path)
如果文件本身是符号链接,则返回信息。
更多信息可以在boost 文档中找到。