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?
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?
As is so often the case, Boost has a library that does what you want. Here's a tutorial.
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.
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
.
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.