如何在 c++ 中生成独立于操作系统的路径
我有一个目标路径和一个字符串文件名,我想用 c++ 将它们连接起来。
有没有办法做到这一点,让程序/编译器在 Windows 或 UNIX 系统的 / 和 \ 之间进行选择?
I have a destination path and a file name as strings and I want to concatenate them with c++.
Is there a way to do this and let the program/compiler choose between / and \ for windows or unix systems?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你想在编译时执行此操作,你当然可以这样做,
或者你可以只使用“/”,并且在 Windows 上一切都会正常工作(除了解析字符串并且仅使用“\”的旧程序)。 只有以这种方式向用户显示时,它才会看起来很有趣。
If you wanted to do it at compile time you could certainly do something like
Or you could just use '/' and things will work just fine on windows (except for older programs that parse the string and only work with '\'). It only looks funny if displayed to the user that way.
正如常见的情况一样,Boost 有一个库可以满足您的需求。 这里是一个教程。
As is so often the case, Boost has a library that does what you want. Here's a tutorial.
在内部到处使用“/”。 然后编写一组实用函数,使用“/”导入任一形式的路径。 编写一个“本机路径”函数,其中包含系统特定的 ifdef 和必要的转换。 可以按需调用。
Use '/' internally everywhere. Then write a set of utility functions which imports a path of either form into using '/'. Write a 'native path' function which has the system specific ifdefs and necessary conversions. that can be called on demand.
执行您要求的一种简单方法是使用一个小型(可能是内联)函数,该函数使用预处理器魔术来确定平台(
#ifdef WIN32
等)并返回适当的分隔符。答案有点复杂,因为还有其他比分隔符更显着的差异。 Windows 文件系统可以有多个根(C:\、D:\ 等),而在 Unix 领域,整个 FS 的根位于 / 。
最好的建议可能是使用
boost: :文件系统
。One simple way to do what you asked is to have a small (probably inline) function that uses preprocessor magic to determine the platform (
#ifdef WIN32
, etc.) and returns the appropriate delimiter character.The answer is a little more complicated because there are other more significant differences than the delimiter character. Windows file systems can have multiple roots (C:\, D:\, etc.), while the whole FS is rooted at / in Unix-land.
The best advice might be to use
boost::filesystem
./
是可移植的(自 XP 起适用于 Windows)为了安全起见,从 C++17 开始:
std::filesystem::path::preferred_separator
,成员常量。请参阅:https://en.cppreference.com/w/cpp/filesystem/path< /a>
使用
std::filesystem::path
对象。操作的完成就像处理字符串一样。 可以通过
operator/=
连接,例如,
结果:
abc/def/hijklm
/
is portable (works for windows since XP)To be on the safe side, from C++17 onwards:
std::filesystem::path::preferred_separator
, a member constant.See: https://en.cppreference.com/w/cpp/filesystem/path
Use a
std::filesystem::path
object.Actions are done as if dealing with strings. Concatenation is possible via
operator/=
e.g.,
Outcome:
abc/def/hijklm