在文件描述符上调用fstat()并检查文件的模式:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
// ...
int fd = open(filename, O_RDONLY)
if (fd == -1) {
// open() failed.
}
struct stat buf;
if (fstat(fd, &buf) != 0) {
// fstat() failed.
}
if (S_ISDIR(buf.st_mode)) {
// It's a directory.
}
Run Code Online (Sandbox Code Playgroud)
这是所有便携式POSIX代码.
请注意,您可以filename在调用open()之前使用stat ().但这可能会导致文件在stat()和open()调用之间发生变化,这意味着你打开()一个不同的文件,然后是你用stat()检查的文件.使用fstat()可以提供弹性,因为即使文件描述符被删除,它仍然会指向正确的文件.