遵循 C 中的符号链接
我正在编写一个 C 程序,给定符号链接的名称,该程序将打印链接指向的文件或目录的名称。关于如何开始有什么建议吗?
I'm looking to write a C program which, given the name of symbolic link, will print the name of the file or directory the link points to. Any suggestions on how to start?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
前面提到的 readlink() 函数是答案的一部分。但是,您应该注意它可怕的接口(它不会以 null 终止响应字符串!)。
您可能还想查看
realpath()
函数,该函数的使用已在 SO 1563186。您还可以在 IIUG Software Archive 中查看“linkpath”的代码。它分析解析符号链接时遇到的所有目录的安全性 - 它使用readlink()
和lstat()
和stat()
;测试程序时的检查之一是确保realpath()
将名称解析为同一文件。The
readlink()
function that has been mentioned is part of the answer. However, you should be aware of its horrid interface (it does not null terminate the response string!).You might also want to look at the
realpath()
function, the use of which was discussed in SO 1563186. You could also look at the code for 'linkpath' at the IIUG Software Archive. It analyzes the security of all the directories encountered as a symbolic link is resolved - it usesreadlink()
andlstat()
andstat()
; one of the checks when testing the program was to ensure thatrealpath()
resolved the name to the same file.确保您有一个支持 POSIX 函数的环境,包括
unistd.h
,然后使用 readlink 函数。Make sure that you have an environment which supports POSIX functions, include
unistd.h
and then use the readlink function.根据平台的不同,
stat()
或fstat()
可能是首先要尝试的方法。如果您使用的是 Linux 或 cygwin,那么stat
程序将为您提供系统 API 调用的合理预期(它几乎为您提供了文本转储)。Depending on the platform,
stat()
orfstat()
are probably the first things to try out. If you're on Linux or cygwin then thestat
program will give you a reasonable idea of what to expect from the system API call (it pretty much gives you a text dump of it).您想要的系统调用是 readlink()。获取链接的路径,返回存储在链接中的字符串(不始终是文件系统中的有效路径!)。有关详细信息,请查看手册页(“man 2 readlink”)。
请注意,您的问题有些含糊不清。您可能会问如何辨别文件系统中的“真实”路径,这有点复杂。
The system call you want is readlink(). Takes a path to the link, returns the string (not always a valid path in the filesystem!) stored in the link. Check the man page ("man 2 readlink") for details.
Note there is some ambiguity to your question. You might be asking for how to tell the "real" path in the filesystem, which is a little more complicated.