以 ~ 开头的 C++ 路径 [英] C++ paths beginning with ~

查看:69
本文介绍了以 ~ 开头的 C++ 路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在 c++ 代码中使用以~"开头的路径?例如,此代码无法正常工作:

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;
}

推荐答案

我猜你是在 Linux 或 POSIX 系统上,具有交互式 shell 理解 ~(例如 bash)

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

实际上,以 ~ 开头的文件路径几乎不会发生(您可以在 shell 中使用 mkdir '~' 创建这样一个目录,但那样会不合常理).请记住,您的 shell 是 globbing 参数,所以你的shell(不是你的程序!)正在用替换~,例如/home/martin 当您在终端中输入 myprogram ~/example.txt 作为命令时.请参阅glob(7).您可能想要使用 glob(3)wordexp(3) 在你的 C++ 程序中(但你需要做所以只有当 "~/example.txt" 字符串来自一些数据 - 例如一些配置文件,一些用户输入等...)

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...)

有时,您可能只需使用 getenv(3) 获取主目录(或 getpwuid(3)使用 getuid(2)).也许你会这样做

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);

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

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

另见这个.

这篇关于以 ~ 开头的 C++ 路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆