Robert Graffham
Robert Graffham

Reputation: 185

What's a good, cross-platform way to concatenate paths in C?

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:

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.

Upvotes: 5

Views: 1740

Answers (3)

Dmitri
Dmitri

Reputation: 9385

Apparently GLib has some functions (like g_build_path) and macros (G_DIR_SEPARATOR_S and others) for this.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215387

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".

Upvotes: 7

Amal Antony
Amal Antony

Reputation: 6817

Unfortunately, there is no such function in the Standard C library to join file paths. You'll have to do it manually.

Upvotes: 1

Related Questions