Obtain platform's path separator using Boost.Filesystem
Solution 1
As of version 1.57, Boost now has a better solution, that is just constant char
/ wchar_t
( dependent on different platforms ): boost::filesystem::path::preferred_separator
.
Read http://www.boost.org/doc/libs/release/libs/filesystem/doc/reference.html#Operating-system-examples for more information. There are even more system-dependent features in it.
Simple example:
#include <boost/filesystem.hpp>
#include <iostream>
int main() {
std::cout << boost::filesystem::path::preferred_separator << std::endl;
}
Solution 2
It seems like boost::filesystem::path::make_preferred
is the ticket:
Effects: The contained pathname is converted to the preferred native format. [Note: On Windows, the effect is to replace slashes with backslashes. On POSIX, there is no effect. -- end note]
Example:
namespace bfs = boost::filesystem;
bfs::path slash("/");
bfs::path::string_type preferredSlash = slash.make_preferred().native();
Solution 3
Haven't tested this, but it looks like you should be able to use this on a recent boost:
http://www.boost.org/doc/libs/1_43_0/libs/filesystem/doc/reference.html
#include <boost/filesystem.hpp>
#include <iostream>
int main() {
std::cout << boost::filesystem::slash<boost::filesystem::path>::value << std::endl;
}
Related videos on Youtube
Emile Cormier
An electrical engineer that turned into a programmer. I'm the author of CppWAMP, a C++11 client library for the WAMP protocol.
Updated on June 04, 2022Comments
-
Emile Cormier over 1 year
Is there a way to obtain the platform's path separator character using Boost.Filesystem? By path separator, I mean
/
for Unix and\
for Windows.I already know I can use
boost::filesystem::path::operator/
to concatenate two paths together with the appropriate separator character. But I just want either/
or\
.I also know I can use
#ifdef _WIN32
, but I'd prefer that Boost.Filesystem tell me the appropriate separator character.EDIT: I want to use version 3 of the Boost.Filesystem API, as used in Boost 1.48.
-
Xeo almost 12 yearsJust so you know, Windows accepts
/
as the pafh separator. -
fefe almost 12 yearsOn WinXP, with VS2010, boost 1.48.0, the return value is "/".
-
-
Emile Cormier almost 12 yearsSadly,
slash
no longer seems to be part of the API. -
KindDragon over 10 years
-
AI0867 over 9 yearsOn windows this will fail to compile, as native() will return std::wstring. That's irrelevant for the purposes of this question though.
-
Emile Cormier over 9 years@AI0867: Thanks, I replaced
std::string
withbfs::path::string_type
in the example. -
tom almost 9 yearsA quick look through the boost source reveals that boost just uses an ifdef to get the seperator during the preprocessor stage. In this instance there is no need to use boost but also, if they are on a non-standard filesystem on a *nix box then boost will incorrecly assume /.