如何判断文件或目录是否存在?
我正在尝试制作一个处理文件和目录的简单程序,但我有两个主要问题:
- 如何检查文件或目录是否存在,以及
- 如何知道它是否是文件、目录、符号链接,设备、命名管道等?目前主要是文件和目录很重要,但我也想了解其他内容。
编辑:所有建议使用 stat()
或类似函数的人,我已经研究过它,虽然它可能回答我的第一个问题,但我无法弄清楚它会如何回答第二个......
I am trying to make a simple program that handles files and directories, but I have two major problems:
- how can I check whether a file or directory exists or not, and
- how do I know if it is a file, directory, symbolic link, device, named pipe etc.? Mainly file and directories matter for now, but I'd like to know the others too.
EDIT: Too all of those who are suggesting to use stat()
or a similar function, I have already looked into that, and while it might answer my first question, I can't figure out how it would answer the second...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您正在询问命名管道/符号链接等,因此您可能在 *nix 上,因此请使用
lstat() 函数
文档 此处了解您可以使用的 S_ISXXX 宏。
Since you're inquiring about named pipes/symlinks etc, you're probably on *nix, so use the
lstat() function
Se docs here for the S_ISXXX macros you can use.
stat() 函数应该为您提供您正在寻找的所有内容(或更具体地说
lstat()
因为stat()
将跟随链接)。The stat() function should give you everything you are looking for (or more specifically
lstat()
sincestat()
will follow the link).使用 stat (或者如果您想获取有关符号链接的信息lstat)
NAME
,而不是跟随它并获取有关目的地的信息stat - 获取文件状态
概要
描述
stat() 函数应获取有关指定文件的信息并将其写入 buf 参数指向的区域。路径参数指向命名文件的路径名。不需要指定文件的读、写或执行权限。在实现定义的条件下,提供附加或备用文件访问控制机制的实现可能会导致 stat() 失败。特别是,系统可能会否认路径指定的文件的存在。
如果指定的文件是符号链接,则 stat() 函数应使用符号链接的内容继续进行路径名解析,并且如果文件存在,则应返回与结果文件相关的信息。
buf 参数是一个指向 stat 结构的指针,如标头中所定义,其中放置了有关文件的信息。
Use stat (or if you wish to get information about a symbolic link instead of following it and getting information about the destination, lstat)
NAME
stat - get file status
SYNOPSIS
DESCRIPTION
The stat() function shall obtain information about the named file and write it to the area pointed to by the buf argument. The path argument points to a pathname naming a file. Read, write, or execute permission of the named file is not required. An implementation that provides additional or alternate file access control mechanisms may, under implementation-defined conditions, cause stat() to fail. In particular, the system may deny the existence of the file specified by path.
If the named file is a symbolic link, the stat() function shall continue pathname resolution using the contents of the symbolic link, and shall return information pertaining to the resulting file if the file exists.
The buf argument is a pointer to a stat structure, as defined in the header, into which information is placed concerning the file.