以 ~ 开头的 C++ 路径

C++ paths beginning with ~

这里是否有可能在 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 在您的 C++ 程序中是 globbing arguments, so your shell (not your program!) is replacing ~ with e.g. /home/martin when you type myprogram ~/example.txt as a command in your terminal. See glob(7). You probably want to use glob(3) or wordexp(3)(但只有当 "~/example.txt" 字符串来自某些数据时才需要这样做——例如某些配置文件、某些用户输入等。 ..)

有时,您可能只使用 getenv(3) to get the home directory (or getpwuid(3) with getuid(2))。也许你可以

std::string home=getenv("HOME");
std::string path= home+"/example.txt";
ofstream myfile(path);

如果你是认真的,你应该检查 getenv("HOME") 不 return NULL。实际上,这不太可能发生。

另见 this