macos 如何获取文件名命令行参数的完整路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1661982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:30:53  来源:igfitidea点击:

How do I get the full path for a filename command-line argument?

c++clinuxmacos

提问by Roland Rabien

I've found lots of libraries to help with parsing command-line arguments, but none of them seem to deal with handling filenames. If I receive something like "../foo" on the command line, how do I figure out the full path to the file?

我找到了很多库来帮助解析命令行参数,但它们似乎都没有处理文件名。如果我在命令行上收到类似“../foo”的信息,我该如何找出文件的完整路径?

回答by AraK

You could use boost::filesystemto get the absolute pathof a file, from its relative path:

您可以使用它boost::filesystem来获取absolute path文件的relative path

namespace fs = boost::filesystem;
fs::path p("test.txt");
fs::path full_p = fs::complete(p); // complete == absolute
std::cout << "The absolute path: " << full_p;

回答by pmg

POSIX has realpath().

POSIX 有realpath().

#include <stdlib.h>
char *realpath(const char *filename, char *resolvedname);

DESCRIPTION
The realpath()function derives, from the pathname pointed to by filename, an absolute pathname that names the same file, whose resolution does not involve ".", "..", or symbolic links. The generated pathname is stored, up to a maximum of {PATH_MAX} bytes, in the buffer pointed to by resolvedname.

描述
真实路径()函数导出,从路径指向的文件名,绝对路径名称相同的文件,其分辨率不涉及“‘’..”,或符号链接。所生成的路径名被存储,直到最大的{PATH_MAX}字节,缓冲器中的指向resolvedname

回答by Ivan

In shell scripts, the command "readlink -f" has the functionality of realpath().

在 shell 脚本中,命令“readlink -f”具有 realpath() 的功能。