views:

246

answers:

4

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?

+6  A: 

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

David Seiler
Do I really need a "whole" library for the choice between / and \?
Janusz
No, but that isn't the only difference between DOS and Unix filenames. Indeed, the slashes are accepted by DOS (as well as backslashes) - but not by the cmd.exe command interpreter.
Jonathan Leffler
Boost is practically the C++ standard library. It's not just any "whole" library.
rlbond
+3  A: 

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.

jcopenha
I haven't tested it yet with a windwos machine but if it works this is enough for me.
Janusz
As far as it goes, it will work. Be aware that DOS paths can start with a drive letter and a colon (otherwise, they are relative to the current drive). And beware alternative 'forks', and device names.
Jonathan Leffler
Windows is actually ok with the forward slash.
Jim Buck
+1  A: 

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.

Drew Hall
+1  A: 

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.

Brian