Janusz
Janusz

Reputation: 189444

How to generate a OS independent path in c++

I have a destination path and a file name as strings and I want to concatenate them with c++.

Is there a way to do this and let the program/compiler choose between / and \ for windows or unix systems?

Upvotes: 8

Views: 5443

Answers (5)

Mykola Tetiuk
Mykola Tetiuk

Reputation: 375

  1. / is portable (works for windows since XP)

  2. To be on the safe side, from C++17 onwards: std::filesystem::path::preferred_separator, a member constant.

See: https://en.cppreference.com/w/cpp/filesystem/path


Use a std::filesystem::path object. Actions are done as if dealing with strings. Concatenation is possible via operator/=

e.g.,

std::filesystem::path myPath = "abc/def";
myPath /= "hij"; // after a slash
myPath += "klm"; // no slash prepended

std::cout << myPath.c_str() << '\n';

Outcome: abc/def/hijklm

Upvotes: 1

Brian
Brian

Reputation: 81

Use '/' internally everywhere. Then write a set of utility functions which imports a path of either form into using '/'. Write a 'native path' function which has the system specific ifdefs and necessary conversions. that can be called on demand.

Upvotes: 2

Drew Hall
Drew Hall

Reputation: 29047

One simple way to do what you asked is to have a small (probably inline) function that uses preprocessor magic to determine the platform (#ifdef WIN32, etc.) and returns the appropriate delimiter character.

The answer is a little more complicated because there are other more significant differences than the delimiter character. Windows file systems can have multiple roots (C:\, D:\, etc.), while the whole FS is rooted at / in Unix-land.

The best advice might be to use boost::filesystem.

Upvotes: 1

jcopenha
jcopenha

Reputation: 3975

If you wanted to do it at compile time you could certainly do something like

#ifdef WIN32
#define OS_SEP '\\'
#else
#define OS_SEP '/'
#endif

Or you could just use '/' and things will work just fine on windows (except for older programs that parse the string and only work with '\'). It only looks funny if displayed to the user that way.

Upvotes: 8

David Seiler
David Seiler

Reputation: 9705

As is so often the case, Boost has a library that does what you want. Here's a tutorial.

Upvotes: 7

Related Questions