开发者

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

开发者 https://www.devze.com 2023-04-11 01:10 出处:网络
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 #def

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 / everywher开发者_开发知识库e 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号