c++std-filesystem

std::filesystem rel. path + remove_filename() results in empty string - Bug or feature?


I have the following code.
What it does is from a relative Path it should remove the filename.
My expected result would be ".\png" what I get is an empty string...

#include <iostream>
#include <filesystem>
#include <string>

//using namespace std;
namespace fs = std::filesystem;

#define VNAME(xx) (#xx)

int main() {

  std::cout << "Hello World!" << "\n";

  std::string fpath = ".\\png\\DUMMY-AB-42-L.PNG";
  auto fs_fpath = fs::path(fpath);
  auto fs_fpath_str = fs_fpath.string();

  std::cout << VNAME(fpath) << ":=" << fpath << "\n";
  std::cout << VNAME(fs_fpath_str) << ":=" << fs_fpath_str << "\n";

  fs_fpath.remove_filename();
  fs_fpath_str = fs_fpath.string();
  std::cout << VNAME(fs_fpath_str) << ":=" << fs_fpath_str << "\n";

  return 0;
}

the output is:

Hello World!  
fpath:=.\png\DUMMY-AB-42-L.PNG  
fs_fpath_str:=.\png\DUMMY-AB-42-L.PNG  
fs_fpath_str:=  

The simple Question is: Bug or Feature ?


Solution

  • Backslash ( \ ) characters are valid in directory and file names on Unix.

    So, on Unix, ".\\png\\DUMMY-AB-42-L.PNG" is a just a filename, without directory.

    With "./png/DUMMY-AB-42-L.PNG", you will have expected output (on both Unix and windows).

    Demo

    or use

    auto fs_fpath = fs::path(".") / "png" / "DUMMY-AB-42-L.PNG";