At the moment, I have a path_concat(char* path_fragment_a, char* path_fragment_b) function, which simply concatenates together path_fragment_a, PATH_DIVIDER, and path_fragment_b. (PATH_DIVIDER is #defined in an #ifdef block, so it’s \ on Windows and / everywhere else.)
But I can’t help thinking this seems:
- a bit of a kludge.
- something which must surely be covered by a fairly common library, which would be better to use if available, so I’m not reinventing the wheel.
Googling it just turned up a lot of results about Python’s os.path.join (which would be ideal, except it’s Python, not C), so I was wondering if anyone was aware of a cleaner/more standard solution.
First of all, you should use
snprintf, not concatenation operations, to construct a string all at once. This is the safe and efficient way. Concatenation may be idiomatic in script languages but it’s inefficient and harmful (prone to dangerous errors) in C.With that said, ever since the first version of DOS that had directories (2 or 3; I forget which it was),
'/'has been valid as a path separator on DOS, and it has always been valid on Windows as well. The only reason it was not used is that many legacy command line programs designed before DOS supported directories interpret'/'as a “switch” (option) character in their command line parsing. The only real-world system in the past 20 years not to support'/'as a path separator is pre-OSX MacOS, and I don’t think that’s a viable target anymore, so in my opinion, you should simply always use'/', and avoid polluting your code with gratuitous “portability”.