【问题标题】:How to distinguish a file pointer points to a file or a directory?如何区分文件指针指向文件还是目录?
【发布时间】:2013-09-13 17:36:12
【问题描述】:

当我这样做时:

FILE * fp = fopen("filename", "r");`  

如何知道文件指针 fp 指向文件或目录?因为我认为这两种情况 fp 都不会为空。我能做些什么?

环境是 UNIX。

【问题讨论】:

    标签: c file unix fopen


    【解决方案1】:

    我在附近找到了这个:

    #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;
      }
      

      【讨论】:

      • 如果我们决定使用statfamily,为什么不直接使用呢?为什么要额外打电话给fileno?
      • @KingsIndian:因为问题是这样问的:“...知道文件指针 fp 指向...”。
      • 我只有 fp,没有文件名 仅在有这样的限制时才适用(例如,API 只通过 fp,而不是文件名)。否则,总会有一个可用的文件名。在 OP 的示例中,他确实有文件名。事实上,如果我们有其中之一,我们可以获得fp、fd、filename 中的两个(诚然,这与您拥有的相同)。但我怀疑这个问题有这样的限制。
      【解决方案3】:

      在 Windows 上,调用 GetFileAttributes,并检查 FILE_ATTRIBUTE_DIRECTORY 属性。

      检查this 和this。

      【讨论】:

        猜你喜欢
        • 2021-01-13
        • 1970-01-01
        • 2019-12-09
        • 1970-01-01
        • 2021-11-06
        • 1970-01-01
        • 2011-04-24
        • 2012-08-12
        • 2016-03-05
        相关资源
        最近更新 更多