当我执行以下操作时:
FILE * fp = fopen("filename", "r");`
我该如何知道文件指针fp指向的是一个文件还是一个目录?因为我认为在两种情况下,fp都不会为空。我该怎么办?
环境是UNIX。
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
int main (int argc, char *argv[]) {
int status;
struct stat st_buf;
status = stat ("your path", &st_buf);
if (status != 0) {
printf ("Error, errno = %d\n", errno);
return 1;
}
// Tell us what it is then exit.
if (S_ISREG (st_buf.st_mode)) {
printf ("%s is a regular file.\n", argv[1]);
}
if (S_ISDIR (st_buf.st_mode)) {
printf ("%s is a directory.\n", argv[1]);
}
}
fileno()
获取已打开文件的文件描述符,然后使用文件描述符上的 fstat()
来返回一个 struct stat
结构体。st_mode
包含有关文件的信息。#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
FILE * pf = fopen("filename", "r");
if (NULL == pf)
{
perror("fopen() failed");
exit(1);
}
{
int fd = fileno(pf);
struct stat ss = {0};
if (-1 == fstat(fd, &ss))
{
perror("fstat() failed");
exit(1);
}
if (S_ISREG (ss.st_mode))
{
printf ("Is's a file.\n");
}
else if (S_ISDIR (ss.st_mode))
{
printf ("It's a directory.\n");
}
}
return 0;
}
stat
家族,为什么不直接使用它们?为什么要额外调用fileno
? - P.Pfp
、fd
、filename
中的两个(这显然等价于您所拥有的)。但我怀疑问题中不存在这样的限制。 - P.P