C++ paths beginning with ~ [duplicate]

南楼画角 提交于 2019-12-01 04:12:21

问题


Is here any possibility to use paths beginning with "~" in c++ codes in linux? For example this code is not working correctly:

#include <iostream>
#include <fstream>
using namespace std;

int main () 
{
  ofstream myfile;
  myfile.open ("~/example.txt");
  myfile << "Text in file .\n";
  myfile.close();
  return 0;
}

回答1:


I guess you are on a Linux or POSIX system, with an interactive shell understanding ~ (e.g. bash)

Actually, files paths starting with ~ almost never happens (you could create such a directory with mkdir '~'in the shell, but that would be perverse). Remember that your shell is 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) inside your C++ program (but you need to do so only if the "~/example.txt" string comes from some data - e.g. some configuration file, some user input, etc...)

Sometimes, you might simply use getenv(3) to get the home directory (or getpwuid(3) with getuid(2)). Perhaps you might do

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

If you are serious, you should check that getenv("HOME") does not return NULL. In practice, that is unlikely to happen.

See also this.



来源:https://stackoverflow.com/questions/33544123/c-paths-beginning-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!