在C中加入文件系统路径

时间:2012-02-10 15:50:51

标签: c filesystems path-separator

类似于python如何具有方便的os.path.join()功能,我想知道在C中是否有一个很好的跨平台方法。

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

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

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:4)

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

答案 2 :(得分:0)

对于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
相关问题