Convert relative path to full path in C++

Alec Jacobson

December 21, 2015

weblog/

Here's one way to convert a relative path like ~/Downloads/../Documents/file.txt to an absolute path /Users/ajx/Documents/file.txt

#include <stdlib.h>
#include <iostream>
...
std::string filename = [](const char * rel_path)
{
  char *real_path = realpath(rel_path, NULL);
  std::string filename = real_path;
  free(real_path);
  return filename;
}(mxArrayToString(prhs[0]));

Unfortunately this seems to crash MATLAB when inserted into a C++ Mex file.

This worked:

string filename;
{
  wordexp_t exp_result;
  wordexp(mxArrayToString(prhs[0]), &exp_result, 0);
  filename = exp_result.we_wordv[0];
}