How to generate a OS independent path in c++

ぐ巨炮叔叔 提交于 2019-12-06 23:13:31

问题


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?


回答1:


If you wanted to do it at compile time you could certainly do something like

#ifdef WIN32
#define OS_SEP '\\'
#else
#define OS_SEP '/'
#endif

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.




回答2:


As is so often the case, Boost has a library that does what you want. Here's a tutorial.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/1056364/how-to-generate-a-os-independent-path-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!