[英]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_concat(char* path_fragment_a, char* path_fragment_b)
函数,它简单地将path_fragment_a
, PATH_DIVIDER
和path_fragment_b
连接在一起。 (PATH_DIVIDER is #defined in an #ifdef block, so it's \\
on Windows and /
everywhere else.) (PATH_DIVIDER在#ifdef块中是#defined,因此在Windows和
/
其他任何地方都是\\
。)
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. 谷歌搜索它只是发现了很多关于Python的
os.path.join
的结果(这将是理想的, 除了它的Python,而不是C ),所以我想知道是否有人知道更清洁/更标准的解决方案。
First of all, you should use snprintf
, not concatenation operations, to construct a string all at once. 首先,您应该使用
snprintf
而不是连接操作来一次构造一个字符串。 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.
连接在脚本语言中可能是惯用的,但在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. 话虽如此,自从DOS的第一个版本有目录(2或3;我忘了它是什么)以来,
'/'
在DOS上作为路径分隔符有效,并且它在Windows上也一直有效。 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. 它没有被使用的唯一原因是在DOS支持的目录之前设计的许多遗留命令行程序在其命令行解析中将
'/'
解释为“switch”(选项)字符。 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". 过去20年中唯一不支持
'/'
作为路径分隔符的真实世界系统是OSX之前的MacOS,我不认为这是一个可行的目标,因此在我看来,你应该总是使用'/'
,并避免以无偿的“可移植性”污染您的代码。
Unfortunately, there is no such function in the Standard C library to join file paths. 遗憾的是,标准C库中没有这样的函数来连接文件路径。 You'll have to do it manually.
你必须手动完成。
显然,GLib有一些功能(如g_build_path
)和宏( G_DIR_SEPARATOR_S
等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.