<分区>
是否有可能在 linux 的 c++ 代码中使用以“~”开头的路径?例如,此代码无法正常工作:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("~/example.txt");
myfile << "Text in file .\n";
myfile.close();
return 0;
}
<分区>
是否有可能在 linux 的 c++ 代码中使用以“~”开头的路径?例如,此代码无法正常工作:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("~/example.txt");
myfile << "Text in file .\n";
myfile.close();
return 0;
}
最佳答案
我猜您使用的是 Linux 或 POSIX 系统,具有理解 ~
(例如 bash
)的交互式 shell
实际上,以 ~
开头的文件路径几乎不会发生(您可以在 shell 中使用 mkdir '~'
创建这样的目录,但那样做是有悖常理的)。请记住,您的外壳是 globbing参数,所以你的 shell(不是你的程序!)正在用 替换 ~
,例如/home/martin
当您在终端中键入 myprogram ~/example.txt
作为命令时。参见 glob(7) .您可能想使用 glob(3)或 wordexp(3)在你的 C++ 程序中(但只有当 "~/example.txt"
字符串来自某些数据时你才需要这样做 - 例如一些配置文件,一些用户输入等......)
有时,您可能只是使用 getenv(3)获取主目录(或 getpwuid(3) 和 getuid(2) )。也许你会做
std::string home=getenv("HOME");
std::string path= home+"/example.txt";
ofstream myfile(path);
如果你是认真的,你应该检查 getenv("HOME")
是否返回 NULL
。实际上,这不太可能发生。
另见 this .
关于以 ~ 开头的 C++ 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33544123/