4

类似于 python 具有便捷os.path.join()功能的方式,我想知道在 C 中是否有一个很好的跨平台方法可以做到这一点。

我目前的方法是使用类似这样的东西设置一些预处理器指令

#ifdef defined(linux)
#define PATH_SEPARATOR "/"
#else
#define PATH_SEPARATOR "\\"
#endif
4

3 回答 3

4

我很确定许多跨平台库都有这样的功能。也许你想看看 APR 的apr_filepath_merge函数。

在 C++ 中,您可以使用 Boost:

#include <boost/filesystem.hpp>
using namespace boost::filesystem;

[...]    

path path1("/tmp");
path path2("example");
path result = path1 / path2;
于 2012-02-10T15:59:28.483 回答
4

没有标准的方法可以做到这一点。自己做或使用图书馆。例如,Apache Portable Runtime 提供apr_filepath_merge

于 2012-02-10T16:01:30.717 回答
1

对于 C,您可以使用cwalk,这是一个小的跨平台库来执行与文件路径相关的事情(cwk_path_joincwk_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
于 2019-04-11T13:58:13.253 回答