cfilesystemspath-separator

Joining filesystem paths in C


Similar to how python has the convenient os.path.join() function, I was wondering if there was a good cross-platform way to do this in C.

My current approach is to set up some preprocessor directives with something like this

#ifdef defined(linux)
#define PATH_SEPARATOR "/"
#else
#define PATH_SEPARATOR "\\"
#endif

Solution

  • I'm pretty sure many cross-platform libraries have such functionality. Maybe you want to have a look at APR's apr_filepath_merge function.

    In C++, you could use Boost:

    #include <boost/filesystem.hpp>
    using namespace boost::filesystem;
    
    [...]    
    
    path path1("/tmp");
    path path2("example");
    path result = path1 / path2;