类似于 python 具有便捷os.path.join()
功能的方式,我想知道在 C 中是否有一个很好的跨平台方法可以做到这一点。
我目前的方法是使用类似这样的东西设置一些预处理器指令
#ifdef defined(linux)
#define PATH_SEPARATOR "/"
#else
#define PATH_SEPARATOR "\\"
#endif
类似于 python 具有便捷os.path.join()
功能的方式,我想知道在 C 中是否有一个很好的跨平台方法可以做到这一点。
我目前的方法是使用类似这样的东西设置一些预处理器指令
#ifdef defined(linux)
#define PATH_SEPARATOR "/"
#else
#define PATH_SEPARATOR "\\"
#endif
我很确定许多跨平台库都有这样的功能。也许你想看看 APR 的apr_filepath_merge函数。
在 C++ 中,您可以使用 Boost:
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
[...]
path path1("/tmp");
path path2("example");
path result = path1 / path2;
没有标准的方法可以做到这一点。自己做或使用图书馆。例如,Apache Portable Runtime 提供apr_filepath_merge。
对于 C,您可以使用cwalk,这是一个小的跨平台库来执行与文件路径相关的事情(cwk_path_join或cwk_path_join_multiple):
#include <cwalk.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char buffer[FILENAME_MAX];
cwk_path_join("hello/there", "../world", buffer, sizeof(buffer));
printf("The combined path is: %s", buffer);
return EXIT_SUCCESS;
}
输出:
The combined path is: hello/world