代码之家  ›  专栏  ›  技术社区  ›  adhanlon

是否有一种简单的方法来判断文件流是否打开了目录而不是文件?

  •  0
  • adhanlon  · 技术社区  · 16 年前

    我正在创建一个HTTP服务器,当我获取文件的路径时,他们请求我用以下方式打开它:

    returned_file = fopen(path, "r");
    

    这(与我想的相反)成功了,即使路径是一个目录。是否有一种简单的方法来检查返回的文件流是否是目录而不是文件?

    4 回复  |  直到 16 年前
        1
  •  0
  •   Wevah    16 年前

    你能检查一下路径是否指向一个目录吗 之前 你叫FOPEN?

        2
  •  4
  •   Eld    16 年前

    可以对fopen返回的文件描述符使用fstat。

    编辑: 下面是示例程序:

    #include <sys/stat.h>
    #include <stdio.h>
    
    void printISDir( FILE* fp, char const * name ) {
      int fdes = fileno(fp) ;
      struct stat fileInfo ;
      fstat(fdes, &fileInfo ) ;
      if ( S_ISDIR(fileInfo.st_mode ) ) {
        printf("%s: I'm a dir!\n", name ) ;
      } else {
        printf("%s: I'm a file!\n", name ) ;
      }
    
    }
    
    int main( int argc, char** argv ) {
      char const * directoryName = "/etc" ;
      char const * fileName = "/etc/hosts" ;
    
      FILE* dirFp = fopen(directoryName, "r") ;
      FILE* fileFp = fopen(fileName, "r") ;
      printISDir( dirFp, directoryName ) ;
      printISDir( fileFp, fileName ) ;
      fclose(dirFp) ;
      fclose(fileFp) ;
    
      return 0 ;
    }
    
        3
  •  4
  •   allenporter    16 年前

    详细说明其他答案后,您可以对返回的文件描述符调用fstat并检查 st_mode 对于 S_IFDIR 比特。s砗isdir helper宏有助于:

      #include <sys/stat.h>
    

      FILE* f = fopen(path, "r");
    
      struct stat buf;
      if (fstat(fileno(f), &buf) == -1) {
        perror("fstat");
      } else {
        if (S_ISDIR(buf.st_mode)) {
          printf("is directory\n");
        } else {
          printf("not directory\n");
        }
      }
    
        4
  •  0
  •   Richard Pennington    16 年前

    打开文件名之前,请使用stat()或fstat()文件描述符fileno(返回的文件)。