这里是否有可能在 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 系统上,具有交互式 shell 理解~
(例如bash
)
实际上,以开头的文件路径~
几乎从未发生过(您可以在 shell 中创建这样的目录mkdir '~'
,但那将是不正当的)。请记住,您的 shell 是全局参数,因此当您在终端中键入命令时,您的 shell(不是您的程序!)将替换~
为eg 。参见glob(7)。您可能想在您的 C++ 程序中使用glob(3)或wordexp(3) (但只有当字符串来自某些数据时才需要这样做- 例如某些配置文件、某些用户输入等...)/home/martin
myprogram ~/example.txt
"~/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
。在实践中,这不太可能发生。
另请参阅此。