如何在主目录中创建文件夹?
我想创建一个目录 path = "$HOME/somedir"
。
我尝试过使用 boost::filesystem::create_directory(path) ,但它失败了 - 显然该函数不会扩展系统变量。
我怎样才能以最简单的方式做到这一点?
(注意:在我的情况下,字符串 path
是常量,我不确定它是否包含变量)
编辑:我正在 Linux 上工作(尽管我计划移植我的应用程序)不久的将来将升级到 Windows)。
I want to create a directory path = "$HOME/somedir"
.
I've tried using boost::filesystem::create_directory(path)
, but it fails - apparently the function doesn't expand system variables.
How can I do it the simplest way?
(note: in my case the string path
is constant and I don't know for sure if it contains a variable)
edit: I'm working on Linux (although I'm planning to port my app to Windows in the near future).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 getenv 获取环境变量,包括
HOME
。如果您不确定它们是否存在,则必须解析字符串来查找它们。您还可以使用系统 shell 和 echo 让 shell 为您执行此操作。
Getenv 是可移植的(来自标准 C),但在 *nix 和 Windows 之间使用 shell 来执行此操作会更困难。 *nix 和 Windows 之间的环境变量约定也有所不同,但该字符串可能是一个配置参数,可以针对给定平台进行修改。
如果您只需要支持扩展主目录而不是任意环境变量,则可以使用
~
约定,然后使用~/somedir
作为配置字符串:此行为复制自Python 的 os.path.expanduser,除了它只处理当前用户。可以通过检查目标平台来改进与平台无关的尝试,而不是盲目地尝试不同的环境变量,即使
USERPROFILE
、HOMEDRIVE
和HOMEPATH
不太可能在 Linux 上设置。Use getenv to get environment variables, including
HOME
. If you don't know for sure if they might be present, you'll have to parse the string looking for them.You could also use the system shell and echo to let the shell do this for you.
Getenv is portable (from standard C), but using the shell to do this portably will be harder between *nix and Windows. Convention for environment variables differs between *nix and Windows too, but presumably the string is a configuration parameter that can be modified for the given platform.
If you only need to support expanding home directories rather than arbitrary environment variables, you can use the
~
convention and then~/somedir
for your configuration strings:This behavior is copied from Python's os.path.expanduser, except it only handles the current user. The attempt at being platform agnostic could be improved by checking the target platform rather than blindly trying different environment variables, even though
USERPROFILE
,HOMEDRIVE
, andHOMEPATH
are unlikely to be set on Linux.从我的头顶上下来,
Off the top of my head,