boost::filesystem::exists() fails when specifying relative path from a file

Viewed 832

Suppose I have the following function defined and used to check whether a required file is available based on the path provided to it.

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;
}

Suppose D:\my_file\require_file.txt exists and, when calling this function with following an absolute path to file as argument, it fails always

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

but when specifying absolute path to parent folder of root file as argument this works as expected,

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

It is also possible to open the required_file.txt when using D:\my_files\this_folder\that_folder\root.file....\required_file.txt in explorer.

Environment:

  • Boost : 1.69
  • Visual Studio 2017
  • Windows 10, 2004

I was confused about whether it was some boost implementation issue or expected behavior.

2 Answers

Like I commented, you need to check your working directory and access. Relative paths will be interpreted relative to the "current working directory".

You can transform an absolute path to a relative one e.g. https://www.boost.org/doc/libs/1_64_0/libs/filesystem/doc/reference.html#op-relative or https://en.cppreference.com/w/cpp/filesystem/relative

Next up, use forward slashes or properly escape your backslashes:

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

If you enable warnings the compiler should tell you about invalid escape sequences

There is nothing wrong with boost::filesystem::exists() function here.

According to your example require_file.txt exists in "D:\\my_files\\this_folder\\that_folder\\..\\..\\require_file.txt" where in terms of absolute path it is "D:\\my_files\\require_file.txt", please keep this actual location in mind for further explanation.

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

So the constructed relative path is "D:\\my_files\\this_folder\\that_folder\\root.file\\..\\..\\require_file.txt" in terms of absolute path it is "D:\\my_files\\this_folder\\require_file.txt". So you are checking in wrong path, that's why exists() function always returns false.

Related