问题
I want to open a file with my program, and I want to use shell symbols to make it easier for me to locate the file. Is there an easy way to have the shell expand out my file path before I use it on runtime. I'm looking for a function that does this.
~/.foo.bar
-> /home/someuser/.foo.bar
Is there some easy way to have the shell preprocess the paths to files before opening the file?
回答1:
You can use wordexp:
#include <wordexp.h>
std::string wordexp(std::string var, int flags = 0)
{
wordexp_t p;
if(!wordexp(var.c_str(), &p, flags))
{
if(p.we_wordc && p.we_wordv[0])
var = p.we_wordv[0];
wordfree(&p);
}
return var;
}
int main()
{
std::cout << wordexp("~/test") << '\n';
}
来源:https://stackoverflow.com/questions/31035974/use-shell-symbols-in-directory-path