std::filesystem::current_path();

Started by
2 comments, last by a light breeze 4 months, 3 weeks ago

I am trying to print the current dir with this code:

  std::filesystem::path path = std::filesystem::current_path();
  std::cout << "Current working directory: " << path << std::endl;

However, it prints out:

Current working directory: "C:\\Users\\Owner\\source\\repos\\fgetctest\\fgetctest"

Why does it have two backslashes instead of one?

Also, why does it start and end with quotes?

Thank you.

Mike C.http://www.coolgroups.com/zoomer/http://www.coolgroups.com/ez/
Advertisement

Compatiblity.

On POSIX derived systems a single backslash is a legal file system character. If it has a double backslash it works correctly in both environments.

From the standard on path separators, “If this character is repeated, it is treated as a single directory separator: /usr///////lib is the same as /usr/lib.” Windows has \ for the character, so for the \\ or any other number of backslashes, they condense to a single backslash on the system path. The OS also handles it correctly. It is slightly harder for humans, but better parsed for interoperability when paths cross operating system boundaries.

A little more info here: https://en.cppreference.com/w/cpp/filesystem/path/make_preferred

frob said:

On POSIX derived systems a single backslash is a legal file system character. If it has a double backslash it works correctly in both environments.

A little more info here: https://en.cppreference.com/w/cpp/filesystem/path/make_preferred

No, it has nothing to do with that. Backslashes are legal file name characters in POSIX, but this also applies to sequences of multiple backslashes. In fact, all sequences of one or more characters except the null character and the forward slash are legal file name characters in POSIX.

What's actually happening is described here:

std::quoted is used so that spaces do not cause truncation when later read by stream input operator

This means:

  • The path is enclosed with quote characters (").
  • Any quote characters in the path itself are replaced by the sequence backslash quote (\").
  • Any backslashes in the path itself are replaced by double backslashes (\\).

Note that this transformation only happens on input/output. Internally there is only a single backslash.

This topic is closed to new replies.

Advertisement