如何区分文件指针指向的是文件还是目录?

6
当我执行以下操作时:
FILE * fp = fopen("filename", "r");`  

我该如何知道文件指针fp指向的是一个文件还是一个目录?因为我认为在两种情况下,fp都不会为空。我该怎么办?

环境是UNIX。

3个回答

3
我找到了这个附近的内容:
#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]);
    }
}

2
你可以使用 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.P
@KingsIndian:因为问题正在询问它:“*...知道文件指针fp指向一个...*”。 - alk
只有当存在这种限制(例如API仅传递fp而不是filename)时,“我只有fp,没有filename”才适用。否则,在某个地方总会有文件名可用。在OP的示例中,他确实有文件名。事实上,如果我们拥有其中一个,我们可以得到fpfdfilename中的两个(这显然等价于您所拥有的)。但我怀疑问题中不存在这样的限制。 - P.P

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接