【问题标题】:boost::filesystem::exists() fails when specifying relative path from a fileboost::filesystem::exists() 在指定文件的相对路径时失败
【发布时间】:2020-11-12 19:48:03
【问题描述】:

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

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。

环境:

  • 提升:1.69
  • Visual Studio 2017
  • Windows 10、2004

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

【问题讨论】:

  • 检查您的工作目录并访问
  • 您不能将.. 附加到普通文件名,只能附加到目录。
  • @n.'pronouns'm。是的,这是有道理的。但是如果在 Windows 资源管理器中尝试,这种情况是有效的。
  • 是的,您可以在 Windows 资源管理器中执行此操作。现在呢?
  • 正如你所说,相对路径应该来自工作目录,而不是文件。

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


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 感谢重播,更正了反斜杠问题。但是我对访问问题有点困惑,如果是当前工作目录访问的情况,那么两个语句都应该失败吧?
【解决方案2】:

这里boost::filesystem::exists()函数没有错。

根据您的示例require_file.txt 存在于"D:\\my_files\\this_folder\\that_folder\\..\\..\\require_file.txt" 中,就绝对路径而言它是"D:\\my_files\\require_file.txt",请记住这个实际位置以便进一步解释。

if ( !boost::filesystem::exists( "D:\\my_files\\this_folder\\that_folder\\root.file\\..\\..\\require_file.txt"))
{
    return false;
}

所以构造的相对路径是"D:\\my_files\\this_folder\\that_folder\\root.file\\..\\..\\require_file.txt",就绝对路径而言,它是"D:\\my_files\\this_folder\\require_file.txt"。所以你检查了错误的路径,这就是为什么exists()函数总是返回false。

【讨论】:

    猜你喜欢
    • 2011-01-13
    • 2012-04-27
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    相关资源
    最近更新 更多