首页 > 解决方案 > boost::filesystem::exists() 在指定文件的相对路径时失败

问题描述

假设我定义了以下函数,并用于根据提供给它的路径检查所需文件是否可用。

bool check_my_file_exists( const std::wstring& my_root_file ) 
{
    const std::wstring file_path = L"..\\..\\require_file.txt";
    const std::wstring relative_path_to_required_file = my_root_file + L"\\" + file_path;
    
    if ( !boost::filesystem::exists( relative_path_to_required_file ))
    {
        return false;
    }

    return true;
}

假设D:\my_file\require_file.txt存在,并且当以文件的绝对路径作为参数调用此函数时,它总是失败

check_my_file_exists( L"D:\\my_files\\this_folder\\that_folder\\root.file" ); // return false

但是当指定根文件的父文件夹的绝对路径作为参数时,这可以按预期工作,

check_my_file_exists( L"D:\\my_files\\this_folder\\that_folder" ); // return true 

在资源管理器中使用 D:\my_files\this_folder\that_folder\root.file....\required_file.txt 时也可以打开 required_file.txt。

环境:

我对这是一些提升实施问题还是预期的行为感到困惑。

标签: c++visual-c++boost

解决方案


就像我评论的那样,您需要检查您的工作目录和访问权限。相对路径将相对于“当前工作目录”进行解释。

您可以将绝对路径转换为相对路径,例如https://www.boost.org/doc/libs/1_64_0/libs/filesystem/doc/reference.html#op-relativehttps://en.cppreference.com /w/cpp/文件系统/相对

接下来,使用正斜杠或正确转义反斜杠:

const std::wstring file_path = L"..\\..\\require_file.txt";
check_my_file_exists( L"D:\\my_files\\this_folder\\that_folder" ); // return true 

如果您启用警告,编译器应该告诉您无效的转义序列


推荐阅读