How to create an OS-independent path in C ++

I have a destination path and a file name as a string, and I want to combine them with C ++.

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

+7
c ++ filesystems cross-platform
source share
4 answers

If you want to do this at compile time, you can do something like

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

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

+7
source share

As often happens, Boost has a library that does what you want. Here is the tutorial.

+7
source share

Use '/' inland. Then write a set of utility functions that imports a path of any shape into the use of '/'. Write a native path function that has system-specific ifdefs and necessary transformations. which can be called upon request.

+2
source share

One easy way to do what you asked is to have a small (possibly built-in) function that uses preprocessing magic to determine the platform ( #ifdef WIN32 , etc.) and returns the corresponding delimiter character.

The answer is a bit more complicated because there are other more significant differences than the delimiter character. Windows file systems can have several roots (C: \, D: \, etc.), and the whole FS is bound to / in Unix-land.

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

+1
source share

All Articles