简体   繁体   中英

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:

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

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

显然,GLib有一些功能(如g_build_path )和宏( G_DIR_SEPARATOR_S等)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM