4

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
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
Scott Frazer
  • 2,145
  • 2
  • 23
  • 36

3 Answers3

4

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;
AndiDog
  • 68,631
  • 21
  • 159
  • 205
4

There is no standard way to do this. Do it yourself or use a library. For example the Apache Portable Runtime provides apr_filepath_merge.

1

For C, you could use cwalk which is a little cross-platform library to do file path related things (either cwk_path_join or cwk_path_join_multiple):

#include <cwalk.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  char buffer[FILENAME_MAX];

  cwk_path_join("hello/there", "../world", buffer, sizeof(buffer));
  printf("The combined path is: %s", buffer);

  return EXIT_SUCCESS;
}

Outputs:

The combined path is: hello/world
Julius
  • 1,155
  • 9
  • 19